Home >Java >javaTutorial >Java reflection advanced
We usually use reflection The first way, first let’s take a look at Class.forName(clssName):
Note: The incoming className must be Full path of the class, otherwise an error java.lang.ClassNotFoundException
will be reported.
public static Class<?> forName(String className) throws ClassNotFoundException { return forName0(className, true, ClassLoader.getCallerClassLoader()); }
By calling the forName0 method, use ClassLoader.getCallerClassLoader()
to load ClassLoader
// Returns the invoker's class loader, or null if none. // NOTE: This must always be invoked when there is exactly one intervening // frame from the core libraries on the stack between this method's // invocation and the desired invoker. static ClassLoader getCallerClassLoader() { // NOTE use of more generic Reflection.getCallerClass() Class caller = Reflection.getCallerClass(3); // This can be null if the VM is requesting it if (caller == null) { return null; } // Circumvent security check since this is package-private return caller.getClassLoader0(); }
After getting the ClassLoader, call claser.getClassLoader0() this is a private package that avoids security checks.
// Package-private to allow ClassLoader access native ClassLoader getClassLoader0();
We usually use reflection The first way, first let’s take a look at Class.forName(clssName):
Note : The passed in className must be the full path of the class, otherwise an error java.lang.ClassNotFoundException
will be reported.
public static Class<?> forName(String className) throws ClassNotFoundException { return forName0(className, true, ClassLoader.getCallerClassLoader()); }
By calling the forName0 method, use ClassLoader.getCallerClassLoader()
to load ClassLoader
// Returns the invoker's class loader, or null if none. // NOTE: This must always be invoked when there is exactly one intervening // frame from the core libraries on the stack between this method's // invocation and the desired invoker. static ClassLoader getCallerClassLoader() { // NOTE use of more generic Reflection.getCallerClass() Class caller = Reflection.getCallerClass(3); // This can be null if the VM is requesting it if (caller == null) { return null; } // Circumvent security check since this is package-private return caller.getClassLoader0(); }
After getting the ClassLoader, call claser.getClassLoader0() this is a private package that avoids security checks.
// Package-private to allow ClassLoader access native ClassLoader getClassLoader0();
The above is the content of advanced reflection in java. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!