代码成就万世基积沙镇海,梦想永在凌云意意气风发|

又一岁荣枯

园龄:3年4个月粉丝:11关注:6

Java反射设置可以访问私有成员

定义一个测试类

public class User {

    private String name = "ppp";
    private String sex;
    private int age;

    private void eat(String num){
        System.out.println("我在"+this.name+"sadasd"+num);
    }

    public void drink(String witer){
        System.out.println("我正在喝"+witer);
    }

    public void setAge(int age) {
        this.age = age;
    }

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

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public String getSex() {
        return sex;
    }
}

使用反射使能访问私有属性

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class FanShe {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //获取类对象
        Class user = Class.forName("Demo01_static.User");
        //获取实例
//        User o =(User)user.newInstance();
        User o = new User();

        //获取类中的方法
        Method eat = user.getDeclaredMethod("eat",String.class);
        //获取类中的属性
        Field name = user.getDeclaredField("name");

        //设置私有属性使其可以更改
        name.setAccessible(true);
        System.out.println(name.get(o));
        name.set(o,"kkkk");
        System.out.println(name.get(o));

        //设置私有方法使其可以修改
        eat.setAccessible(true);
        eat.invoke(o,"16");


    }

}

本文作者:又一岁荣枯

本文链接:https://www.cnblogs.com/java-six/p/16813336.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   又一岁荣枯  阅读(27)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起