zoukankan      html  css  js  c++  java
  • Java反射使用技巧

    1. 通过setAccessible关闭安全检查,关闭的目的不是因为访问的field/method是私有的,而且因为关闭后访问公有方法也不会再有安全检查.

    SomeObject someObject = new SomeObject();  
    
    Class<? extends SomeObject> cls = SomeObject.class;  
    
    Method method = cls.getDeclaredMethod("someGetMethod");  
    
    method.setAccessible(Boolean.TRUE); 
    
    String xxx = (String) method.invoke(someObject); 

    2.把已经查找好的method/field 缓存起来,毕竟类的结构一般是不会变化的.

    public Method getMethod(String name, @SuppressWarnings("rawtypes") Class... parameterTypes) throws SecurityException, NoSuchMethodException {  
    
        Method method = classMethodMap.get(name);//classMethodMap used to store method
        
        if (method == null) {  
                method = someClass.getDeclaredMethod(name, parameterTypes);//someClass is the reflect object class  
                method.setAccessible(Boolean.TRUE);  
                concentrationClassMethodMap.put(name, method);  
            }  
        return method;  
    }
  • 相关阅读:
    & 微信支付对比
    # MySQL性能优化技巧
    & mysql简单定时增量全量备份
    & Mysql高级总结
    python面向对象
    django虚拟环境的安装
    Python 内置函数
    Python列表解析式
    函数练习
    Python装饰器
  • 原文地址:https://www.cnblogs.com/princessd8251/p/5283854.html
Copyright © 2011-2022 走看看