zoukankan      html  css  js  c++  java
  • java反射访问private属性和方法

    Private类中有私用成员变量和私有方法,正常情况下外部类是无法访问私有方法和改变私有成员变量的值

    public class Private {

        private String names = "zs";
        private String sayHello(String name){
            return "say:"+name;
        }
        
        public String getNames(){
            return names;
        }
    }

    通过反射可实现对私有方法的访问和改变私有成员变量的值

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

    public class TestPrivate01 {

        public static void main(String[] args) throws Exception {
            Private p = new Private();
            //Private p2 = new Private();
            //System.out.println(p.getClass()==p2.getClass());
            Class<?> classType = p.getClass();
            
            Method privatemethod = classType.getDeclaredMethod("sayHello", new Class[]{String.class});
            Field field = classType.getDeclaredField("names");
            //将访问权限控制检查压制(suppress)
            privatemethod.setAccessible(true);
            field.setAccessible(true);
            
            field.set(p, "ls");
            System.out.println(privatemethod.invoke(p, new Object[]{"Hello"}));
            System.out.println(p.getNames());    
        }
    }

  • 相关阅读:
    【codevs4919】线段树练习4
    【51Nod1405】树上距离和 二次扫描与换根法
    【洛谷P1717】钓鱼
    【洛谷P1230】智力大冲浪
    【洛谷P1248】加工生产调度
    hdu 1195(搜索)
    hdu 1181(Floyed)
    hdu 1250(大整数)
    hdu 1180(广搜好题)
    hdu 1099(数学)
  • 原文地址:https://www.cnblogs.com/charleszhang1988/p/3051421.html
Copyright © 2011-2022 走看看