Reflector 2 - Field, simple implementation and partial source code analysis

Value isAccessible () Gets this object is accessible flags, people say, then that is "Allow get, set". `` `@CallerSensitive public Field getField (String name) throws NoSuchFieldException, SecurityException {// checkMemberAccess secure authentication and access checks the java, //Reflection.getCallerClass () can be acquired call this method allow the reflected class // PUBLIC checkMemberAccess (Member.PUBLIC, Reflection.getCallerClass (), true); Field field = getField0 (name); if (field == null) {throw new NoSuchFieldException (name);} return field;} `` `` `` private void checkMemberAccess (int which, Class caller, boolean checkProxyInterfaces) {// java security manager, access control and access control to prevent unknown java program is run malicious code on the system have an impact //https://docs.oracle.com /javase/8/docs/api/java/lang/SecurityManager.html final SecurityManager s = System.getSecurityManager (); // exception null if (! s = null) {// Get returns final ClassLoader loader calls the class ccl = ClassLoader.getClassLoader (caller); (! IsInterface ())}} // recursive search parent if {Class c = getSuperclass (); if (! C = null) {if (! (Res = c.getField0 (name)) = null) {return res ;}}} return null;} `` `##### digression, reflected on the speed difference between said first conclusion," (under normal conditions, that is, in the case of my example) setAccessible (true) will be closed java security check, greatly enhance the reflection rate. " `` `Public class reflectSpeed ​​{public static void main (String [] args) throws Exception {SecurityManager sm = new SecurityManager (); sm.checkMemberAccess (Person.class, Member.DECLARED); Person person = (Person) Class.forName ( "main.java.Person") newInstance ();. person.setName ( "firstName"); Method method = person.getClass () getMethod ( "getName");. // getName is public, it does not require the setAccessible ( true) long start = System.currentTimeMillis (); for (int i = 0; i <10000000; i ++) {method.invoke (person);} System.out.println ( "simple:" + (System.currentTimeMillis () -start));

Guess you like

Origin www.cnblogs.com/lvdandan/p/10949919.html