使用自己的ClassLoader實現熱替換


轉載自:http://blog.csdn.net/is_zhoufeng/article/details/26602689

首先實現一個自己的ClassLoader,該ClassLoader重寫findClass方法。 從classpath中加載類資源。 

注意,不要重寫loadClass方法。  因為在使用自定義的MyClassLoader加載Person類的時候 。  Person類中需要依賴的其他對象, 都會默認使用MyClassLoader的loadClass方法進行加載。  如果重寫了loadClass方法(像下面代碼注釋那樣),就會導致jvm使用MyClassLoader來加載Object、String等等一些類。  當然,這些類在classpath是找不到的。 所以就會拋出ClassNotFoundException 。

import java.io.ByteArrayOutputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.IOException;  
import java.nio.ByteBuffer;  
import java.nio.channels.FileChannel;  
  
public class MyClassLoader extends ClassLoader{  
  
//  @Override  
//  public Class<?> loadClass(String name) throws ClassNotFoundException {  
//      return findClass(name);  
//  }  
      
    @Override  
    protected Class<?> findClass(String name) throws ClassNotFoundException {  
        String classPath = MyClassLoader.class.getResource("/").getPath(); //得到classpath  
        String fileName = name.replace(".", "/") + ".class" ;  
        File classFile = new File(classPath , fileName);  
        if(!classFile.exists()){  
            throw new ClassNotFoundException(classFile.getPath() + " 不存在") ;  
        }  
        ByteArrayOutputStream bos = new ByteArrayOutputStream() ;  
        ByteBuffer bf = ByteBuffer.allocate(1024) ;  
        FileInputStream fis = null ;  
        FileChannel fc = null ;  
        try {  
            fis = new FileInputStream(classFile) ;  
            fc = fis.getChannel() ;  
            while(fc.read(bf) > 0){  
                bf.flip() ;  
                bos.write(bf.array(),0 , bf.limit()) ;  
                bf.clear() ;  
            }  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }finally{  
            try {  
                fis.close() ;  
                fc.close() ;  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return defineClass(bos.toByteArray() , 0 , bos.toByteArray().length) ;  
    }  
  
  
  
  
}  

現在來寫一個Person類。  用與被MyClassLoader加載

public class Person {  
      
    public void sayHello(){  
        System.out.println("hello world!");  
    }  
  
}  

然后寫個測試類來測試。每隔1s就加載一下hot.Person類。 

當StartUp測試類啟動后, 我們可以手動修改personClass類, 並修改sayHello方法的內容。   將會看到熱替換的效果。

 

注意, 測試類中在加載hot.Person的時候,使用的是myclassLoader的findClass方法。 而不是loadClass方法, 因為loadClass方法由於雙親委派模式,會將hot.Person交給myClassLoader的父ClassLoader進行加載。 而其父ClassLoader對加載的Class做了緩存,如果發現該類已經加載過, 就不會再加載第二次。  就算改類已經被改變

 

注意:同一個ClassLoader不能多次加載同一個類。 如果重復的加載同一個類 , 將會拋出 loader (instance of  hot/MyClassLoader): attempted  duplicate class definition for name: "hot/Person" 異常。  所以,在替換Class的時候,  加載該Class的ClassLoader也必須用新的。 

import java.lang.reflect.InvocationTargetException;  
import java.lang.reflect.Method;  
  
public class StartUp {  
      
    public static void main(String[] args) throws ClassNotFoundException {  
          
        int i = 0 ;  
          
        while(true){  
            MyClassLoader mcl = new MyClassLoader() ;  
            System.out.println(mcl.getParent());  
            Class<?> personClass =  mcl.findClass("hot.Person");  
              
            try {  
                Object person =  personClass.newInstance() ;  
                Method sayHelloMethod = personClass.getMethod("sayHello") ;  
                sayHelloMethod.invoke(person) ;  
                System.out.println(++i);  
            } catch (InstantiationException e1) {  
                e1.printStackTrace();  
            } catch (IllegalAccessException e1) {  
                e1.printStackTrace();  
            } catch (SecurityException e) {  
                e.printStackTrace();  
            } catch (NoSuchMethodException e) {  
                e.printStackTrace();  
            } catch (IllegalArgumentException e) {  
                e.printStackTrace();  
            } catch (InvocationTargetException e) {  
                e.printStackTrace();  
            }  
              
            try {  
                Thread.sleep(1000) ;  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }  
        }  
          
    }  
  
}  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM