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;  
}
posted @ 2016-03-16 15:46  princessd8251  阅读(298)  评论(0编辑  收藏  举报