package reflect_;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Reflect{
public static void main(String[] args) {
// test1();
test2("reflect_.Reflect", "add", new Class[] { int.class, int.class }, new Object[] { 10, 50 });
test2("reflect_.Reflect", "add", new Class[] { int.class }, new Object[] { 10 });
// 类名 方法名 参数类型类的数组 对应参数类的参数对象的数组
}
private static void test2(String className, String methodName, Class[] paramType, Object[] paramValue) {
try {
// 1.执行类加载机制
Class clz = Class.forName(className);
// 2.根据方法名,获取方法对象
Method method = clz.getMethod(methodName, paramType);
// 3.创建实例对象
Object obj = clz.newInstance();
// 4.调用对应的成员方法
method.invoke(obj, paramValue);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
private static void test1() {
Reflect r = new Reflect();
r.add(10, 20);
}
public void add(int a, int b) {
System.out.println(a + b);
}
public void add(int a) {
System.out.println(a);
}
}
java反射创建对象
最新推荐文章于 2024-07-11 11:16:19 发布