反射
静态方法反射
拿到类
Class<?> classBook = Class.forName("包名")
拿到方法
Method method = classBook.getMethod("方法名", new Class[]{参数类型.class ...});
调用方法
method.invoke(null, 参数);
方法参数的区别,以及拿方法的区别
-
只有一个String类型参数
public class Book { public static String getValue(String book) { } }
获取方法
// 拿到方法 Method method = classBook.getMethod("getValue", String.class); // 通过 invoke 调用,返回值保存到 object Object object = method.invoke(null, "string");
-
只有一个 boolean 方法
public static String getValue(Boolean value) { System.out.println("getValue:" + value); return "xx"; }
获取方法
// 拿到方法 Method method = classBook.getMethod("getValue", Boolean.class); // 通过 invoke 调用,返回值保存到 object Object object = method.invoke(null, false);
-
多个参数 int 型
public static String getValue(int existingValue, int vibrateType, int vibrateSetting) { }
获取方法
// 拿到方法 Method method = classBook.getMethod("getValue", new Class[]{int.class, int.class, int.class}); // 通过 invoke 调用,返回值保存到 object Object object = method.invoke(null, 1,2,3);
非静态方法
区别在于那里, 可以看到前面 invoke 传的是null, 那么这里就需要传对象了
拿到方法
Class<?> classBook = Class.forName("包名");
Method method = classBook.getMethod("方法名", new Class[]{参数类型.class ...});
调用方法
Object objectInstance = classBook.newInstance();
method.invoke(objectInstance, 参数);