私はクラスの読み込みが初めてなので、何か間違っている場合は助けてください。
スレッド「メイン」の例外 java.lang.ClassNotFoundException: java.net.URLClassLoader.findClass(URLClassLoader.java:381) でこんにちは 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();
}
}
}