英文:
JavaCompiler - Generated class not able to access generated enums
问题
我正在生成类和枚举,生成的代码看起来没问题。生成的枚举位于生成的类的子包中。
生成的类包 - com.pkg1.pkg2
生成的枚举包 - com.pkg1.pkg2.enums
我有一个 Java 测试用例,其中类必须编译。为此,我首先编译枚举。这部分工作正常。现在测试用例失败,类的 setter 方法具有枚举作为输入参数。
- 枚举 Weather 的示例代码:
package com.pkg1.pkg2.enums;
public enum Weather {
SUMMER("summer"),
WINTER("winter");
public final String value;
public Weather(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
- 类 Weather 的示例代码:
package com.pkg1.pkg2;
import com.pkg1.pkg2.enums.Weather;
public interface Weather extends CityWeather {
public void setWeather(Weather weather);
}
- 测试用例的示例代码:
@BeforeClass
public static void beforeAllTestMethods() throws Exception {
/* 前 3 行没有错误 */
String enumsPath = Paths.get("").toAbsolutePath().toString() + "com/pkg1/pkg2/enums/";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, enumsPath + "Weather.java");
/* 下面的代码失败。
error: package com.pkg1.pkg2.enums does not exist
import com.pkg1.pkg2.enums.Weather;
^
*/
String classPath = Paths.get("").toAbsolutePath().toString() + "com/pkg1/pkg2/";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, classPath + "Weather.java");
}
有什么建议吗?
英文:
I am generating both the class and enums, and the generated code looks fine. The generated enums is in sub-package of the generated class.
Generated class package - com.pkg1.pkg2
Generated enum package - com.pkg1.pkg2.enums
I have a java test case where the class has to compile. So for this I compiles the enums first. This works fine. Now the test case fails where the setter methods of the class has enum as input parameters.
-
sample code for Enum-Weather:
package com.pkg1.pkg2.enums;
public enum Weather{
SUMMER("summer"),
WINTER("winter");public final String value;
public Weather(String value) {
this.value = value;
}public String getValue() {
return value;
}}
-
sample code of a class-Weather:
package com.pkg1.pkg2;
import com.pkg1.pkg2.enums.Weather;
public interface Weather extends CityWeather{
public void setWeather(Weather weather);
}
-
Sample code of the test case:
@BeforeClass
public static void beforeAllTestMethods() throws Exception {/* First 3 lines runs without any error */ String enumsPath = Paths.get("").toAbsolutePath().toString()+ "com/pkg1/pkg2/enums/" JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); compiler.run(null,null,null,enumsPath + "Weather.java"); /* The below code fails. error: package com.pkg1.pkg2.enums does not exist import com.pkg1.pkg2.enums.Weather; ^ */ String classPath = Paths.get("").toAbsolutePath().toString()+ "com/pkg1/pkg2/" JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); compiler.run(null,null,null,classPath + "Weather.java");
Any suggestion please.
专注分享java语言的经验与见解,让所有开发者获益!
评论