获取类加载
Class<?> aClass = Class.forName("对应的类名全路径")
加载类方法 getMethod()和getDeclaredMethod()
区别:
- getMethod () 获取的是类的所有公有方法,这就包括自身的所有public方法和从基类继承的、从接口实现的所有public方法。
- getDeclaredMethod() 获取的是类自身声明的所有方法,包含public、protected和private方法,但不能获取基类继承。
- 两者使用方法一样
getMethod(String name) 无参数
getMethod(String name, Class<?>... parameterTypes) 有参 -->getMethod("方法名",int.class,String.class)
setAccessible(boolean) 是否跳过安全权限检查
完整使用方法(单例模式)
try {
Class<?> aClass = Class.forName("com.test.TestClass");
Method testReflect = aClass.getDeclaredMethod("testReflect", int.class, boolean.class);
if(!testReflect.isAccessible()){
testReflect.setAccessible(true);
}
// 单例 获取私有构造方法
Constructor<?> declaredConstructor = aClass.getDeclaredConstructor();
// 跳过安全权限检查
if(!declaredConstructor.isAccessible()){
declaredConstructor.setAccessible(true);
}
// 调用方法
testReflect.invoke(declaredConstructor.newInstance(), 0, true);
// 如果公有 默认构造方法
// testReflect.invoke(aClass.newInstance(), 0, true);
} catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException | ClassNotFoundException e) {
// todo 异常处理
}