我写了一个类加载器,但是加载(loadClass)类后,报错是无法解析加载的类.

解决方案 »

  1.   

    package wxmpackage;
    import java.io.*;public class myClassLoader extends ClassLoader{
    private byte[] getBytes( String fileName )throws IOException{
    File file = new File( fileName );
    long fileLen = file.length();
    byte fileArray[] = new byte[(int)fileLen];
    FileInputStream fin = new FileInputStream(file);
    int r = fin.read(fileArray);
    if( r != fileLen )
    throw new IOException("can't read file");
    fin.close();
    return fileArray;
    }

    private boolean compileFile( String javaFile )throws IOException{
    System.out.println("Compiling"+javaFile);
    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 resolve )throws ClassNotFoundException{
    Class objClass = null;
    objClass = findLoadedClass(name);

    String filedic = name.replace('.','/');
    String javaFileName = filedic+".java";
    String classFileName = filedic+".class";
    File javaFile = new File(javaFileName);
    File classFile = new File(classFileName);
    if( (javaFile.exists() && !classFile.exists()) || (javaFile.lastModified() > classFile.lastModified()))
    {
    try
    {
    if( !compileFile(javaFileName) || !classFile.exists())
    {
    throw new ClassNotFoundException("Compile failed:"+javaFileName);
    }
    }catch( IOException ie )
    {
    throw new ClassNotFoundException(ie.toString());
    }
    }

    //确保已经正确编译或者不需要编译,我们开始加载原始字节
    try
    {
    byte raw[] = getBytes( classFileName );
    objClass = defineClass( name,raw,0,raw.length );
    }catch( IOException ie )
    {
    System.out.println("defineClass:");
    }

    if( objClass == null )
    {
    objClass = findSystemClass(name);
    }
    if( resolve && objClass != null )
    resolveClass(objClass);
    if( objClass == null )
    throw new ClassNotFoundException( name );

    return objClass;

    }
    }
    myClassLoader objClassLoader = new myClassLoader();
    Class clas = objClassLoader.loadClass( accounmeta,true );
      

  2.   

    Process p = Runtime.getRuntime().exec("javac"+javaFile);留个空格
    Process p = Runtime.getRuntime().exec("javac "+javaFile);还有注意你要保证这个文件路径正确就ok我已经测试错了
    ok
      

  3.   

    有一点我不明白,我要装载的类写了一个.java文件,内容是:
    package wxmpackage;public class accounmeta { /**
     * @param args
     */
    public void withdraw( int wmoney )
    {
    System.out.println("in meta");
    System.out.println("there is only 10000");
    }
    public void deposit( int dmoney )
    {
    System.out.println("in meta");
    }
    public static void main(String[] args) {
    // TODO Auto-generated method stub }
    }是不是可以放在任何位置?有没有问题?
      

  4.   

    把包结构去掉javac 编译方式不会生成包结构