java 反射调用私有方法 小例

1.代码

package com.schoolonline.reflect;

public class ReflectEntity {
    private String name = "java";
    private Integer year = 23;
    private String email;

    public Integer getYear() {
        return year;
    }

    public void setYear(Integer year) {
        this.year = year;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getName() {

        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private void sayHello() {
        System.out.println("Hi, everyone!\n my name is " + getName() + ", this is " + getYear() + " years old!");
    }

    @Override
    public String toString() {
        return "ReflectEntity{" +
                "name='" + name + '\'' +
                ", year=" + year +
                ", email='" + email + '\'' +
                '}';
    }
}
package com.schoolonline.reflect;

import java.lang.reflect.Method;

public class ReflectMain {
    public static void main(String[] args) throws Exception {
        Class clazz = Class.forName("com.schoolonline.reflect.ReflectEntity");
        Method method = clazz.getDeclaredMethod("sayHello");
        method.setAccessible(true);
        method.invoke(clazz.newInstance());
    }
}

结果

Hi, everyone!
 my name is java, this is 23 years old!

Process finished with exit code 0

 

 

2.注意,调用私有方法或属性,不设置method.setAccessible(true);
会报如下异常

Exception in thread "main" java.lang.IllegalAccessException: Class com.schoolonline.reflect.ReflectMain can not access a member of class com.schoolonline.reflect.ReflectEntity with modifiers "private"
	at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
	at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:296)
	at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:288)
	at java.lang.reflect.Method.invoke(Method.java:491)
	at com.schoolonline.reflect.ReflectMain.main(ReflectMain.java:9)

3.参考

https://blog.csdn.net/hbcui1984/article/details/2719089

http://www.cnblogs.com/lzq198754/p/5780331.html

你可能感兴趣的:(Java)