0

我是加载类的新手,所以如果有任何问题请帮助我。

线程“main”中的异常 java.lang.ClassNotFoundException:Hello at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424)

class TestClassLoader extends ClassLoader {
 @Override
 public Class<?> loadClass(String name) throws ClassNotFoundException {
     /*if (name.equals("test.Test1"))*/ {
         try {
             InputStream is = Object.class.getClassLoader().getResourceAsStream(name);
             byte[] buf = new byte[10000];
             int len = is.read(buf);
             return defineClass(name, buf, 0, len);
         } catch (IOException e) {
             throw new ClassNotFoundException("", e);
         }
     }
     /*return getParent().loadClass(name);*/
 }
}

public class DynamicCompilerTest {
    public static void main(String[] args) throws Exception {

        String fullName = "Hello";

        // Here we get and specify the source code of the class to be compiled     
        String formuae = "b+a";
        String src = "import I1; public class Hello implements I1 { public int calculate(int a, int b){return "+formuae+";}   public String toString2() {        return \"Hello, I am \"  ;   }}";

        DynamicCompile uCompiler = new DynamicCompile(fullName, src);
        uCompiler.compile();
        I1 aa = (I1) uCompiler.run();
        System.out.println(aa.toString2());
        System.out.println(aa.calculate(5, 5));
        //Hashtable<String, I1> ht = new Hashtable<>();
        MyMap<String, I1> mm = new MyMap<>();
        mm.put("hello", aa);

        myThread th = new myThread();
        th.setHt(mm);
        th.start()  ;
       Thread.sleep(50);
        String src2 = "import I1; public class Hello implements I1 { public int calculate(int a, int b){return a*b;}   public String toString2() {        return \"Hello, I am NEW \"  ;   }}";
      try{ mm.writerLock(); 
             Thread.sleep(2000);
            DynamicCompile uCompiler2 = new DynamicCompile(fullName, src2);
            uCompiler2.compile();

            I1 aa2 = (I1) uCompiler2.run();
            System.out.println(aa2.toString2());
            System.out.println(aa2.calculate(5, 5));
            }   
        finally{
            mm.releaseWriteLock();    
        }
    }
}
4

0 回答 0