Test1.java
----------------------------------------------------------
package ptviewer;
public class Test1 {
public String sayHello()
{
return "hello world";
}
}
=========================================
Test2.java
----------------------------------------------------------------------
package ptviewer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Class c = null;
try {
c = Class.forName("ptviewer.Test1");
// new Class[]{String.class} @ if the method has a String arg
Method method =c.getMethod("sayHello", null);
Object obj = c.newInstance();
// new Object[]{"a string"} @ if the method has a String arg
String s = (String) method.invoke(obj , null);
System.out.println(s);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}
----------------------------------------------------------
package ptviewer;
public class Test1 {
public String sayHello()
{
return "hello world";
}
}
=========================================
Test2.java
----------------------------------------------------------------------
package ptviewer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Class c = null;
try {
c = Class.forName("ptviewer.Test1");
// new Class[]{String.class} @ if the method has a String arg
Method method =c.getMethod("sayHello", null);
Object obj = c.newInstance();
// new Object[]{"a string"} @ if the method has a String arg
String s = (String) method.invoke(obj , null);
System.out.println(s);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
}