[java]代码库
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class ReflectTest
{
public class Worker{
private String name = "";
public void setName(String name){
this.name = name;
}
public void work(){
System.out.println("worker "+name+" will work");
}
}
public static class SWorker{
private String name = "";
public void setName(String name){
this.name = name;
}
public void work(){
System.out.println("s worker "+name+" will work");
}
}
public static void main(String[] args)
{
try{
/*
* 非静态内部类
*/
ClassLoader loader = Thread.currentThread().getContextClassLoader();
//加载内部类名称的写法【包路径.主类名$内部类名】
Class clWorker = loader.loadClass("ReflectTest$Worker");
//通过以下输出语句可以看到,内部类的构造函数需要外部类做参数
System.out.println("worker's cons is:"+clWorker.getDeclaredConstructors()[0]);
Constructor cons = clWorker.getDeclaredConstructor(ReflectTest.class);
Worker worker = (Worker)cons.newInstance(new ReflectTest());
Method setMethod = clWorker.getMethod("setName",String.class);
setMethod.invoke(worker,"张三");
Method workMethod = clWorker.getMethod("work");
workMethod.invoke(worker);
/*
* 静态内部类
*/
Class clSWorker = loader.loadClass("ReflectTest$SWorker");
//获取构造方法不需要加额外参数
Constructor cons1 = clSWorker.getDeclaredConstructor();
SWorker sWorker = (SWorker)cons1.newInstance();
setMethod = clSWorker.getMethod("setName",String.class);
setMethod.invoke(sWorker,"李四");
workMethod = clSWorker.getMethod("work");
workMethod.invoke(sWorker);
}catch(Exception e){
e.printStackTrace();
}
}
}