我基本上試圖做的是調用一個對象的方法,它的類被寫入一個字符串並編譯通過javax.tools.JavaCompiler
這部分是「容易」,我用了類似的東西這個:https://sites.google.com/site/malenkov/java/081217使用雙反射對象
但是,我想調用一個方法的對象是一個不同類中的字段,它也寫在一個String中並通過JavaCompiler編譯。我所擁有的是:
MemoryClassLoader mcl1 = new MemoryClassLoader("Class1", Class1Content);
MemoryClassLoader mcl2 = new MemoryClassLoader("Class2", Class2Content);
Class c1 = mcl1.loadClass("Class1");
Class c2 = mcl2.loadClass("Class2");
Field f = c1.getDeclaredField("current"); //current should be of type Class2
Object obj = f.get(c2.newInstance()); //trying to cast the Field to type Class2 so I can invoke Class2 methods on it
Method m = c2.getDeclaredMethod("Class2Method");
System.out.println(m.invoke(obj));
重要的代碼到Class(又名在字符串變量Class1Content):
Class1Content = "public MemoryClassLoader mcl = new MemoryClassLoader(\"" + "Class2" + "\", Class2Content);\n" +
"Class c = mcl.loadClass(\"" + "Class2" + "\");\n" +
"public Object current;\n" + //the object I will try to invoke a method on
"public Class1()throws Exception{\n" +
"Field f = c.getDeclaredField(\"initialState\");" + // initialState is the name of the field in Class2 I'm trying to have in Class1
"current = f.get(c.newInstance()); c.cast(current);\n" +
"}\n";
當我嘗試運行的一個代碼塊,我得到的線異常Object state = f.get(c2.newInstance());
線程「main」中的異常java.lang.IllegalArgumentException:不能 set java.lang.Object字段Class1.current轉換爲Class2
有沒有什麼辦法可以做到我正在努力實現的目標,還是我必須回到製圖板?
謝謝!
'MemoryClassLoader'是從鏈接? – 2015-03-13 15:28:49
是的,就是那個 – Vlad 2015-03-13 15:29:24