通过反射调用类中的方法
一 ,调用无参方法:
import java.lang.reflect.Method;
public class InvokeSayJapanDemo {
public static void main(String[] args) {
Class<?> c1=null;
try {
c1=Class.forName(PersonZ.class.getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
Method met=c1.getMethod("sayJapan");
met.invoke(c1.newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}
}
二,调用有参方法:
import java.lang.reflect.Method;
public class InvokeSayHelloDemo {
public static void main(String[] args) {
Class<?> c1 = null;
try {
c1 = Class.forName(PersonZ.class.getName());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch bloc
e.printStackTrace();
}
try {
Method method = c1.getMethod("sayHello", String.class, int.class);
String rv = null;
rv = (String) method.invoke(c1.newInstance(), "Von", 32);
System.out.println(rv);
} catch (Exception e) {
e.printStackTrace();
}
}
}