初探Java类加载机制的奥秘

http://tech.ddvip.com   2006年11月27日    社区交流

本文详细介绍初探Java类加载机制的奥秘

  5)如果还没有类,返回 ClassNotFoundException。

  6)否则,将类返回给调用程序。

  三、一个实现了ClassLoader的例子:

/**
*CompilingClassLoader.java
*Copyright 2005-2-12
*/
import java.io.*;
public class CompilingClassLoader extends ClassLoader{
//读取一个文件的内容
private byte[] getBytes(String filename) throws IOException{
 File file=new File(filename);
 long len=file.length();
 byte[] raw=new byte[(int)len];
 FileInputStream fin=new FileInputStream(file);
 int r=fin.read(raw);
 if(r!=len) throw new IOException("Can't read all,"+r+"!="+len);
 fin.close();
 return raw;
}
private boolean compile(String javaFile) throws IOException{
 System.out.println("CCL:Compiling "+javaFile+"...");
 //调用系统的javac命令
 Process p=Runtime.getRuntime().exec("javac "+javaFile);
 try{
  //其他线程都等待这个线程完成
  p.waitFor();
 }catch(InterruptedException ie){
  System.out.println(ie);
 }
 int ret=p.exitValue();
 return ret==0;
}
public Class loadClass(String name,boolean resovle) throws ClassNotFoundException{
 Class clas=null;
 clas=findLoadedClass(name);
 //这里说明了包的表示
 String fileStub=name.replace('.','/');
 String javaFilename=fileStub+".java";
 String classFilename=fileStub+".class";
 File javaFile=new File(javaFilename);
 File classFile=new File(classFilename);
 //如果存在class文件就不编译
 if(javaFile.exists()&&(!classFile.exists()||javaFile.lastModified()>classFile.lastModified())){
  try{
   if(!compile(javaFilename)||!classFile.exists()){
    throw new ClassNotFoundException("ClassNotFoundExcetpion:"+javaFilename);
   }
  }catch(IOException ie){
   throw new ClassNotFoundException(ie.toString());
  }
 }
 try{
  byte[] raw=getBytes(classFilename);
  //通过读入数据来构造一个类结构,这是核心
  clas=defineClass(name,raw,0,raw.length);
 }catch(IOException ie){
  //
 }
 if(clas==null){
  clas=findSystemClass(name);
 }
 System.out.println("findSystemClass:"+clas);
 if(resovle && clas!=null){
  resolveClass(clas);
 }
 if(clas==null){
  throw new ClassNotFoundException(name);
 }
 return clas;
}
}
测试该loader:
/**
*TestRun.java
*Copyright 2005-2-11
*/
import java.lang.reflect.*;
public class TestRun{
 public static void main(String[] args) throws Exception{
  String progClass=args[0];
  String progArgs[]=new String[args.length-1];
  System.arraycopy(args,1,progArgs,0,progArgs.length);
  CompilingClassLoader ccl=new CompilingClassLoader();
  Class clas=ccl.loadClass(progClass);
  //返回一个class的type
  Class[] mainArgType={(new String[0]).getClass()};
  Method main=clas.getMethod("main",mainArgType);
  Object argsArray[]={progArgs};
  main.invoke(null,argsArray);
 }
}

  以上的核心内容已经编写完了,编译后,我们得到两个文件:

  CompilingClassLoader.class,TestRun.class

  四、编写一个例子,然后运行我们的ClassLoader

/**
*Hello.java
*/
public class Hello{
 public static void main(String[] args){
  if(args.length!=1){
   System.err.println("Error,exit!");
   System.exit(1);
  }
  String name=args[0];
  System.out.println("Hello,"+name);
 }
}

  好了,运行java TestRun Hello 阿飞

....
....
....
Hello,阿飞

责编:豆豆技术应用

正在加载评论...