自訂Classloader 載入類---Eclipse plugin開發

來源:互聯網
上載者:User

  在我們的代碼中有很多是動態載入類的,但如果使用eclipse 開發plugin會有一些問題。
  例如:要求在plugin中使用某類型的class,但由於plugin的運行環境和運行時環境不一致,導致你在進行plugin開發時遇到ClassNotFoundException等問題。在這樣的情況下就要自訂ClassLoader然後,在plugin中使用。同時需要注意的一個問題是:在動態家在類的時候,最好不要使用xxx.getClass().getClassLoader()或xxx.class.getClassLoader(),因為這樣一樣可能導致ClassNotFountException,最好是使用Thread.currentThread().getContextClassLoader().
這樣在使用自訂ClassLoader的時候,就不用修改代碼,直接把自訂ClassLoader放到Thread的contextClassLoad中既可。
  ClassLoade的代碼:

/*
 * Created on 2005-12-1
 */
package org.jsports.plugin.classLoader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
import java.util.List;


/**
 * @author Kobye
 */
public class JsportsClassLoader extends ClassLoader {
  private String dir ;
  
  public JsportsClassLoader (ClassLoader parent,String dir){
   super(parent);
   this.dir = dir;
  } 
 
 
 protected Class findClass(String name)throws ClassNotFoundException {
  byte[] bytes = loadClassBytes(name);
  Class theClass = defineClass(name, bytes, 0, bytes.length);
  if (theClass == null){
   throw new ClassFormatError();
  }
  return theClass;
   }


 private byte[] loadClassBytes(String className) throws ClassNotFoundException {
  try {
   String classFile = getClassFile(className);
   FileInputStream fis = new FileInputStream(classFile);
   FileChannel fileC = fis.getChannel();
   ByteArrayOutputStream baos = new
   ByteArrayOutputStream();
   WritableByteChannel outC = Channels.newChannel(baos);
   ByteBuffer buffer = ByteBuffer.allocate(1024);
   while (true) {
    int i = fileC.read(buffer);
    if (i == 0 || i == -1) {
    break;
    }
    buffer.flip();
    outC.write(buffer);
    buffer.clear();
   }
   fis.close();
   return baos.toByteArray();
  } catch (IOException fnfe) {
   throw new ClassNotFoundException(className);
  }
 }


 private String getClassFile(String name){
  StringBuffer sb = new StringBuffer(dir);
  name = name.replace('.', File.separatorChar) + ".class";
  sb.append(File.separator + name);
  return sb.toString();
 }
 

 
 protected URL findResource(String name) {              
  try {                                         
   URL url = super.findResource(name);           
   if (url != null){
    return url;                                   
   }
   url = new URL("file:///" + converName(name)); 
   return url;                                  
      } catch (MalformedURLException mue) {                  
    return null;                                
   }                                           
    }      
 
 
 private String converName(String name) {     
   StringBuffer sb = new StringBuffer(dir);
   name = name.replace('.', File.separatorChar);
   sb.append(File.separator + name);           
   return sb.toString();                       
 }                                            
                                                   

 private String getClassName(String dir,File f){
  String name = f.getAbsolutePath();  
  if(name.startsWith(dir)){ 
   name = name.substring(dir.length(),name.length());
  }
  name = name.replace(File.separatorChar,'.');
  if(name.endsWith(".class")){
   name = name.substring(0,name.length()-".class".length());
  }
  return name;
 }
 private List getAllFiles(File base){
  File[]dirs = base.listFiles(new ClassFileFilter());
  File[]classFile = base.listFiles(new ClassFileNameFilter());
  List files = new ArrayList();
  for(int i=0;i<classFile.length;i++){
   files.add(classFile[i]);
  }
  for(int i=0;i<dirs.length;i++){
   files.addAll(getAllFiles(dirs[i]));
  }
  return files;
 }
 
 private File getDirByName(File dir,String dirName,String baseDir){
  if(!dir.isDirectory()){
   return null;
  }   
  String dirPath = dir.getAbsolutePath(); 
  if(dirPath.startsWith(baseDir)){
   //檢查  該目下的File dir  
   dirPath = dirPath.substring(baseDir.length(),dirPath.length());
   System.out.println();
   if(dirPath.endsWith("model")){
    return dir;
   }
  }
  File[]files = dir.listFiles();
  for(int i=0;i<files.length;i++){
   File f = getDirByName(files[i],dirName,baseDir);
   if(f!=null){
    return f;
   }
  }
  return null;
 }
 
}


這個ClassLoader的功能是把dir路徑下的model目錄中的所有類載入。
然後這樣調用:
  String path = this.getCurrentProject().getLocation().toFile().getAbsolutePath()+"
//bin";
  Thread.currentThread().setContextClassLoader(new JsportsClassLoader (Thread.currentThread().getContextClassLoader(),path));  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.