1. 程式人生 > 實用技巧 >loadClass()、findClass()、defineClass()

loadClass()、findClass()、defineClass()

loadClass()中主要呼叫 findLoadedClass(String)呼叫這個方法

1、使用指定的二進位制名稱來載入

protected Class<?> loadClass(String name, boolean resolve)
    throws ClassNotFoundException
{
    synchronized (getClassLoadingLock(name)) {
        // 首先,檢視這個Class是否已經被載入
        Class<?> c = findLoadedClass(name);
        
//如果沒有被載入,就檢視父類載入器 if (c == null) { long t0 = System.nanoTime(); try { if (parent != null) { //遞迴呼叫loadClass() c = parent.loadClass(name, false); } else { //父類載入器是null,說明是啟動類載入器,查詢對應的Class
c = findBootstrapClassOrNull(name); } } catch (ClassNotFoundException e) { // ClassNotFoundException thrown if class not found // from the non-null parent class loader } //如果都沒有找到 if (c == null
) { // If still not found, then invoke findClass in order // to find the class. //呼叫findClass() long t1 = System.nanoTime(); c = findClass(name); // this is the defining class loader; record the stats sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0); sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1); sun.misc.PerfCounter.getFindClasses().increment(); } } if (resolve) { resolveClass(c); } return c; } }

2、findClass 根據名稱或者位置載入Class位元組碼,然後使用defineClass 通常由子類去實現

protected Class<?> findClass(String name) throws ClassNotFoundException {
    throw new ClassNotFoundException(name);
class NetworkClassLoader extends ClassLoader {
        String host;
        int port;
 
         public Class findClass(String name) {
            byte[] b = loadClassData(name);
             return defineClass(name, b, 0, b.length);
         }
 
         private byte[] loadClassData(String name) {
             // load the class data from the connection
         }

)

3、deineClass() 把位元組碼轉換成Class

protected final Class<?> defineClass(String name, byte[] b, int off, int len)
    throws ClassFormatError
{
    return defineClass(name, b, off, len, null);
}