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;  
}
相關文章
相關標籤/搜索