通过反射机制调用类的方法,主要用到下面的方法:
public Object invoke(Object obj, Object... args)
1
参数:
obj是调用基础方法的实例对象
调用基础方法索要传递的参数,参数是一个变长类型
下面是一个具体的示例:
package thread;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Teacher {
public String getName(String name, String address, Integer age) {
return name + "是一名人民教师,在"+address+","+age+"岁";
}
public static void main(String[] args) {
try {
Class<?> clazz = Class.forName("thread.Teacher");
Method method = clazz.getMethod("getName", String.class, String.class, Integer.class);
Object obj = method.invoke(clazz.newInstance(), "李梅","上海", 21);
System.out.println(obj);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}