我們反射通常使用第一種方式,先來看看Class.forName(clssName):
注意:傳入的className必須是類別的全路徑,否則會報錯java.lang.ClassNotFoundException
。
public static Class<?> forName(String className) throws ClassNotFoundException { return forName0(className, true, ClassLoader.getCallerClassLoader()); }
透過呼叫forName0方法,使用ClassLoader.getCallerClassLoader()
來載入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(); }
在取得ClassLoader呼叫claser.getClassLoader0() 這是一個私有包,可以避免安全檢查。
// Package-private to allow ClassLoader access native ClassLoader getClassLoader0();
我們反射通常使用第一種方式,首先來看看Class.forName(clssName):
注意:傳入的className必須是類別的全路徑,否則會報錯java.lang.ClassNotFoundException
。
public static Class<?> forName(String className) throws ClassNotFoundException { return forName0(className, true, ClassLoader.getCallerClassLoader()); }
透過呼叫forName0方法,使用ClassLoader.getCallerClassLoader()
來載入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(); }
在取得ClassLoader呼叫claser.getClassLoader0() 這是一個私有包,可以避免安全檢查。
// Package-private to allow ClassLoader access native ClassLoader getClassLoader0();
以上就是java反射進階的內容,更多相關內容請關注PHP中文網(www.php.cn)!