随便记两笔Java中的反射

1. 声明对象(调用无参的构造函数)

Class clz = Class.forName("package.ClassName");
Object obj = clz.newInstance();

2. 声明方法

Class clz = Class.forName("package.ClassName");

Method method1 = clz.getMethod("method_without_parameter");
method1.invoke(obj);

Method method2 = clz.getMethod("method_with_parameter", String.Class);

Object obj = clz.newInstance();
method2.invoke(obj, "hello");

3. 参数为数组

Class clz = Class.forName("package.ClassName");

Class[] cl = new Class[1];
cl[0] = String[].class;
Method method = clz.getMethod("run", cl);

Object[] in = new Object[1];
String[] param = new String[1];
param[0] = "hello";
in[0] = param;

Object obj = clz.newInstance();
method.invoke(obj, in);

你可能感兴趣的:(Java)