首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用双反射对象

使用双反射对象
EN

Stack Overflow用户
提问于 2015-03-13 15:25:45
回答 1查看 82关注 0票数 1

基本上,我要做的是在一个对象上调用一个方法,该对象的类是用字符串编写并通过javax.tools.JavaCompiler编译的。

这部分是“容易”的,我使用了类似于此的东西:https://sites.google.com/site/malenkov/java/081217

但是,我想调用方法的对象是另一个类中的一个字段,这个字段也是用字符串编写并通过JavaCompiler编译的。我拥有的是:

代码语言:javascript
运行
复制
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));

Class1中的重要代码(也称为字符串变量Class1Content):

代码语言:javascript
运行
复制
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());行得到一个异常

线程“主”java.lang.IllegalArgumentException中的异常:无法将java.lang.Object字段Class1.current设置为Class2

有什么办法我可以做我想要实现的,还是我必须回到画板上?

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-13 15:37:29

MemoryClassLoader扩展了ClassLoader,因此您的两个类加载了不同的ClassLoaders。除非您指定了ClassLoaders之间的某种关系,否则由一个加载的类将不会被另一个看到。我将尝试修改MemoryClassLoader,以便一个实例可以加载两个类。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29036101

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档