通过反射访问类的私有方法(无参)

Person类:

package com.fanshe.entity;

public class Person {
    private String name;
    private int age;
    
    private void fun(){
        System.out.println("奔跑吧骚年!");
    }
    
    private void fly(){
        System.out.println("要上天!");
    }
}

测试类:

package com.fanshe.test;

import java.lang.reflect.Method;
import org.junit.Test;
import com.fanshe.entity.Person;

public class PersonTest {
    @Test
    public void test1() throws Exception{
        //1.获取Person类的类类型
        //Class c = Person.class;
        Class c = Class.forName("com.fanshe.entity.Person");//在不知道类名的情况下,一般用这种方法,例如Tomcat创建servlet对象,<servlet-class>标签中的类名
        //2.使用类类型创建对象
        //Person p = (Person) c.newInstance();
        Object p = c.newInstance();
        //3.创建一个方法的反射对象
        //Method m = c.getMethod("fun");//这是获取到public的方法,如果是私有方法则会报错
        Method m = c.getDeclaredMethod("fun");//获取私有方法
        //也可以创建方法反射对象数组,这种方法是在不知道Person中方法名的情况下使用
        //Method[] ms = c.getDeclaredMethods();
        //if (ms.length > 0) {
        //    for (Method m : ms) {
        //        //设置对私有方法的访问权限
        //        m.setAccessible(true);
                //执行方法
        //        m.invoke(p);
        //    }
        //}
        //4.设置对私有方法的访问权限
        m.setAccessible(true);
        //5.执行方法
        m.invoke(p);
    }
}

执行结果:

原文地址:https://www.cnblogs.com/wrf-hsj/p/10755992.html