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


  • 相关阅读:
    IIS安装和使用(Windows Server 2003)
    五险一金
    CKEditor与CKFinder的配置(ASP.NET环境)
    spring的@ConditionalOnMissingBean注解
    spring的@Primary注解
    java8实现接口需要重写接口中的default方法吗
    消息队列的作用
    ES快速入门,ElasticSearch 搜索引擎
    spring的@PostConstruct 和 @PreDestroy 注解
    Spring注解@Component、@Repository、@Service、@Controller区别
  • 原文地址:https://www.cnblogs.com/leeeee/p/7276581.html
Copyright © 2011-2022 走看看