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;  
}

相关文章:

  • 2021-05-20
  • 2021-11-07
  • 2021-11-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-04
  • 2022-12-23
  • 2021-05-17
  • 2022-01-23
  • 2021-06-16
  • 2021-11-25
  • 2022-01-12
相关资源
相似解决方案