反射工具类
public class ReflectionsUtils {
//根据一个class 创建一个对象
public static <T> T newInstance(Class<T> clazz){
try { //clazz 待创建的类 T是对象类型
return clazz.newInstance();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
//获取某个类的public方法
public static Method[] getPublicMethods(Class clazz){
Method[] declaredMethod = clazz.getDeclaredMethods();//获取当前类的所有方法 不包括父类方法
List<Method> pmethods = new ArrayList<>();
for (Method method : declaredMethod) {
if(Modifier.isPublic(method.getModifiers())){
pmethods.add(method);
}
}
return pmethods.toArray(new Method[0]);//返回一个Method类型的数组 0是初始化的大小 长度不够会自动扩充
//也可以写成
/* Method[] m = new Method[0];
return pmethods.toArray(m);
*/
}
//调用指定对象的指定方法
//三个参数 分别是 1.被调用的对象 2、被调用的方法 3、方法的参数
public static Object invoke(Object obj,Method method,Object...args){
try {
return method.invoke(obj,args);//如果是静态方法 obj就传null
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
在测试类中测试代码:
public class TestClass {
private String a(){
return "a";
}
public String b(){
return "b";
}
protected String c(){
return "c";
}
}
public void testInvoke() {
//获取到public 方法 也就是b方法
Method[] publicMethods = ReflectionsUtils.getPublicMethods(TestClass.class);
Method bMethods = publicMethods[0];//赋值给bMethods
TestClass testClass = new TestClass();
//执行
Object invoke = ReflectionsUtils.invoke(testClass, bMethods);
//输出b 代表反射工具类代码没问题
System.out.println(invoke);
}