【问题标题】:Compiling a java class with plexus-compiler-eclipse and running it as a JUnit test使用 plexus-compiler-eclipse 编译 java 类并将其作为 JUnit 测试运行
【发布时间】:2012-11-09 08:36:59
【问题描述】:

我目前正在尝试动态生成代码,对其进行编译,然后将其作为 JUnit4 测试运行。我非常接近目标,但我有一个问题可能与 plexus-compiler-eclipse 或我如何加载已编译的类有关。让我解释一下:

  1. 我使用简单的 FileWriterWithEncoding 将 java 代码写入文件
  2. 我使用 EclipseJavaCompiler().performCompile(CompilerConfiguration) 使用 plexus-compiler-eclipse(也尝试使用 plexus-compiler-javac)将它编译为 Java6 代码(源目标兼容)
  3. 我使用URLClassLoader.newInstance(new URL[] {resource }).loadClass("classname") 加载类,其中资源为getClass().getResource("filename")(也尝试使用getClass().forName(className, true, classLoader),其中classLoader 与上面的URLClassLoader 相同)
  4. 然后我使用 JUnitCore 的一个实例来运行我使用 JUnitCore().run 生成的测试类(加载上述类的结果)

在第 4 点之前一切似乎都很好,在该点 JUnit 没有在类上看到任何测试方法(我显然确实在生成的代码中使用 @org.junit.Test 注释了每个测试方法)。调试,我可以看到如果我对加载的类执行 newInstance() 或检查加载的类,我没有注释,没有公共方法,没有声明的字段,SFA !!! newInstance() 只有一个私有成员,这很正常,因为它的引用类型是 Object,但不知何故,我无法强制转换它来尝试调用应该存在的公共方法。

知道我在编译/类加载中缺少什么导致运行时类不完整吗?

提前感谢您的任何想法...

【问题讨论】:

    标签: java compiler-construction junit4 plexus


    【解决方案1】:

    显然,这很简单!我发现 this answer 让我意识到我的 URLClassLoader 缺少父级。

    【讨论】:

      猜你喜欢
      • 2013-07-18
      • 1970-01-01
      • 2011-08-30
      • 2019-03-14
      • 2017-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多