在第三篇已经讲过通过反射实例化对象的方式,这次顺带讲讲实例化对象之后调用该对象的方法。
public class A {
public A(String s){
System.out.println(s);
}
public void method_1(String s){
System.out.println("method_1:"+s+" (String type)");
}
public void method_2(int i){
System.out.println("method_2:"+i+" (int type)");
}
public void method_3(){
System.out.println("method_3 (no parameter)");
}
public void method_4(byte b){
System.out.println("mehtod_4:"+b+" (char type)");
}
}
public class B {
public static void main(String[] args) throws Exception{
Class cls=Class.forName("test.reflect.A"); //import class
Constructor cst=cls.getConstructor(new Class[]{String.class}); //get the constructor
Object obj=cst.newInstance(new Object[]{new String("invoke Construct method!")}); //get a new instance
Method m1=cls.getMethod("method_1",new Class[]{String.class}); //get the method_1
Method m2=cls.getMethod("method_2",new Class[]{int.class}); //get the method_2
Method m3=cls.getMethod("method_3",null); //get the method_3
Method m4=cls.getMethod("method_4",new Class[]{byte.class});
m1.invoke(obj,new Object[]{new String("hello")}); //invoke the method_1
m2.invoke(obj,new Object[]{new Integer(123)}); //invoke the method_2
m3.invoke(obj,null); //invoke the method_3
m4.invoke(obj,new Object[]{new Byte((byte)90)});
Method[] mth=cls.getMethods(); //get all methods
mth[0].invoke(obj,new Object[]{new String("hello")}); //invoke the first method
mth[1].invoke(obj,new Object[]{new Integer(3)}); //invoke the second method
mth[2].invoke(obj,null); //invoke the third method
mth[3].invoke(obj,new Object[]{new Byte((byte)60)});
}
}
应用场景:比如定义一个基类时,需要将方法名称传入,然后自动去调用该方法。