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