zoukankan      html  css  js  c++  java
  • 笔记:setAccessible方法启用/禁用权限控制检查

    class A {

        private int i;

        public int getI(){
           return i;
        }

        private void setI(int i) {
           this.i = i;
        }
    }



     Class<?> clazz= Class.forName("hadoopclient.A");
           
           Field iField =clazz.getDeclaredField("i");
           System.out.println("i: "+iField);
           Method getI = clazz.getMethod("getI", newClass[]{});
           System.out.println("getI: "+getI);
           Method setI = clazz.getDeclaredMethod("setI", newClass[]{int.class});
           System.out.println("setI: "+setI);
           
           Object newInstance = clazz.newInstance();
           
           Object returnValue = getI.invoke(newInstance,newClass<?>[]{});
           System.out.println("init: "+returnValue);
           
           setI.setAccessible(true); //若无此句将抛异常
           setI.invoke(newInstance, newObject[]{100});
           returnValue = getI.invoke(newInstance, newClass<?>[]{});
           System.out.println("invokesetI(100): "+returnValue);
            
        }
    }

    注意:
    setAccessible(true)并不是将方法的访问权限改成了public,而是取消java的权限控制检查。所以即使是public方法,其accessible属相默认也是false

    JDK 文档:

    setAccessible

    public void setAccessible(boolean flag)
                       throws SecurityException
    
    Setthe accessible flag forthis object to the indicated boolean value. A valueof true indicates thatthe reflected object should suppress Java language access checkingwhen it is used. A valueof false indicates thatthe reflected object should enforce Java language access checks.

    First, if there is a security manager,its checkPermission methodis called witha ReflectPermission("suppressAccessChecks") permission.

    SecurityException israisedif flag is true butaccessibility of this object may not be changed (for example, ifthis element object is a Constructor objectfor the class Class).

    SecurityException israised if this object is a Constructor objectfor the class java.lang.Class,and flag istrue.

    Parameters:
    flag - the new value forthe accessible flag
    Throws:
    SecurityException -if the request is denied.
    See Also:
    SecurityManager.checkPermission(java.security.Permission)RuntimePermission


  • 相关阅读:
    BZOJ 4408: [Fjoi 2016]神秘数
    51Nod 1317 相似字符串对
    51Nod 1561 另一种括号序列
    BZOJ 4556: [Tjoi2016&Heoi2016]字符串
    51Nod 1048 整数分解为2的幂 V2
    BZOJ 4698: Sdoi2008 Sandy的卡片
    BZOJ 3571: [Hnoi2014]画框
    BZOJ 2752: [HAOI2012]高速公路(road)
    BZOJ 1095: [ZJOI2007]Hide 捉迷藏
    BZOJ 4537: [Hnoi2016]最小公倍数
  • 原文地址:https://www.cnblogs.com/leeeee/p/7276581.html
Copyright © 2011-2022 走看看