[Java反射机制] 通过反射机制创建类的实例并调用其方法

//通过“反射机制” 创建类的实例
public class ReflectionDemo02 {

public int add(int a, int b) {
return a + b;
}

public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
// 反射第一步:获取要操作类的Class对象
// 获取Class对象的第二种方法、通过.class
Class<?> classType = ReflectionDemo02.class;

// 运行期创建对象
Object obj = classType.newInstance();// 因为泛型给定的是object
// 所以这里实例化的只能是object对象
// 因为是反射 不需要知道他具体的类型、直接获得这个obj的方法(虽然我已知这是ReflectionDemo02类的)
Method method = classType.getMethod("add", int.class, int.class); // 此时获得了add方法

Object result = method.invoke(obj, 2, 5); // 自动装箱
// 此时result真正类型为Integer、虽然真正的方法声明是int、
// 但是对于基本数据类型、永远返回的是其包装类
System.out.println((Integer) result); // 证明其是Integer类型、强制类型转换不会出现异常
}

}
My New Blog : http://blog.fdlife.info/ The more you know, the less you believe.
原文地址:https://www.cnblogs.com/ForDream/p/2324028.html