【发布时间】:2012-11-09 08:36:59
【问题描述】:
我目前正在尝试动态生成代码,对其进行编译,然后将其作为 JUnit4 测试运行。我非常接近目标,但我有一个问题可能与 plexus-compiler-eclipse 或我如何加载已编译的类有关。让我解释一下:
- 我使用简单的 FileWriterWithEncoding 将 java 代码写入文件
- 我使用 EclipseJavaCompiler().performCompile(CompilerConfiguration) 使用 plexus-compiler-eclipse(也尝试使用 plexus-compiler-javac)将它编译为 Java6 代码(源目标兼容)
- 我使用
URLClassLoader.newInstance(new URL[] {resource }).loadClass("classname")加载类,其中资源为getClass().getResource("filename")(也尝试使用getClass().forName(className, true, classLoader),其中classLoader 与上面的URLClassLoader 相同) - 然后我使用 JUnitCore 的一个实例来运行我使用 JUnitCore().run 生成的测试类(加载上述类的结果)
在第 4 点之前一切似乎都很好,在该点 JUnit 没有在类上看到任何测试方法(我显然确实在生成的代码中使用 @org.junit.Test 注释了每个测试方法)。调试,我可以看到如果我对加载的类执行 newInstance() 或检查加载的类,我没有注释,没有公共方法,没有声明的字段,SFA !!! newInstance() 只有一个私有成员,这很正常,因为它的引用类型是 Object,但不知何故,我无法强制转换它来尝试调用应该存在的公共方法。
知道我在编译/类加载中缺少什么导致运行时类不完整吗?
提前感谢您的任何想法...
【问题讨论】:
标签: java compiler-construction junit4 plexus