package com.bixiangdong.api.reflect;
import java.lang.reflect.Method;
//小案例:根据全限定名,使用反射创建对象,运行其中的方法
public class Demo01 {
public static void main(String[] args) throws Exception {
Utils utils = new Utils("com.bixiangdong.api.reflect.Test", "test");
utils.run();
}
}
//工具类,任何类传入其中可以执行指定的方法并创建对象
class Utils{
private String className;
private String methods;
public Utils(String className,String methods){
this.className=className;
this.methods=methods;
}
public void run() throws Exception {
//根据类名获取class对象
Class aClass = Class.forName(className);
Object o = aClass.newInstance();
Method method = aClass.getMethod(methods);
method.invoke(o);
}
}
class Test{
public void test(){
System.out.println("test");
}
}