import operate425.demo.demo1.Student;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 通过反射突破访问修饰符,调用private私有的方法
*
* @author silence
*/
public class ClassMethod {
public static void main(String[] args) throws Exception {
//获得class字节码文件
Class<Student> clazz = Student.class;
//调用私有无参无返回值的方法
//method1(clazz);
//调用私有有参有返回值的方法
//method2(clazz);
//调用公共的有参无返回值的方法
//method3(clazz);
//调用私有无参有返回值的方法
// method4(clazz);
//获取所有的公共的方法,包括父类的方法
// method5(clazz);
//获取所有的公共的和私有的方法 不包含父类的方法
//method6(clazz);
}
private static void method6(Class<Student> clazz) {
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
System.out.println(declaredMethod);
}
}
/**
* 获取公共的方法,包括父类的方法
*
* @param clazz clazz
*/
private static void method5(Class<Student> clazz) {
Method[] methods = clazz.getMethods();
for (Method method : methods) {
System.out.println(method);
}
}
/**
* 调用私有无参有返回值的方法
*
* @param clazz clazz
*/
private static void method4(Class<Student> clazz) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method privatemethod = clazz.getDeclaredMethod("privatemethod");
privatemethod.setAccessible(true);
String invoke = (String) privatemethod.invoke(new Student());
System.out.println(invoke);
}
/**
* 调用公共的有参无返回值的方法
*/
private static void method3(Class<Student> clazz) throws Exception {
//获得单个公共方法引用,方法名, 参数类型
Method setboolean = clazz.getMethod("setboolean", boolean.class);
setboolean.invoke(new Student(), true);
}
/**
* 调用私有有参有返回值的方法
*/
private static void method2(Class<Student> clazz) throws Exception {
//获得对象引用
Method getmethod1 = clazz.getDeclaredMethod("getmethod1", String.class);
//临时修改访问修饰符限制
getmethod1.setAccessible(true);
//对象引用 和方法实参 这里对象引用直接new的一个新对象
Object invoke = getmethod1.invoke(new Student(), "反射实参");
//接收输出返回值
System.out.println(invoke);
}
/**
* 调用私有无参无返回值的方法
*
* @param clazz clazz
* @throws Exception Exception
*/
private static void method1(Class<Student> clazz) throws Exception {
//通过反射创建一个对象 这里获取一个私有的有参数的
Constructor<Student> constructor = clazz.getDeclaredConstructor(int.class);
constructor.setAccessible(true);
//创建对象需要传实参
Student student = constructor.newInstance(23);
//获取一个参数引用, 获取一个私有的 参数名,和参数类型
Method getmethod1 = clazz.getDeclaredMethod("getmethod1");
//私有的方法被调用也需要修改访问修饰符权限
getmethod1.setAccessible(true);
//对象引用,和实参
getmethod1.invoke(student);
}
}
通过反射突破访问修饰符,调用private私有的方法
最新推荐文章于 2022-08-01 15:00:15 发布