我想从用户输入中收集从外部位置实例化的新类对象。程序会询问用户文件的位置,例如/tmp/MyTestClass.java。然后我想它抓住那个.java文件,并在程序中使它成为一个可用的类。所以我可以调用类似MyClass = new MyTestclass()的东西。我一直在环顾四周,似乎无法找到答案,或者它是否可能?任何信息都会有用。
谢谢!
----------- --------------- EDIT
我可能一直在想我的问题。这是一个JUnit测试(抱歉应该之前提到过)。下面是我用来引入静态类的示例。我希望能够从用户输入动态提取JUnit测试文件。 testcastjunit是该类的名称。我需要能够以编程方式从用户输入中获取类并运行测试用例。
org.junit.runner.Result result = JUnitCore.runClasses(**testcastjunit.class**);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
答案 0 :(得分:4)
如果我了解你,这就是你所需要的:
JavaCompiler jCompiler = ToolProvider.getSystemJavaCompiler();
List<String> options = Arrays.asList(
"-d", "./bin/",
path+".java");
int compilationResult = jCompiler.run(null, null, null,
options.toArray(new String[options.size()]));
if (compilationResult == 0) {
mensaje = "Compiled the "+path+" to its .class";
ClassLoader cLoader = ClassLoader.getSystemClassLoader();
try {
cLoader.loadClass("THE CLASS");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} else {
mensaje = "Couldnt compile.";
}
这对你有用:
答案 1 :(得分:1)
感谢Javier的建议,我能够让我的程序动态编译并运行JUnit测试用例。我用它来运行Selenium IDE导出的.java文件。以下是我完成的示例。希望这可以帮助其他寻找类似解决方案的人。另一个注意事项我正在使用Eclipse IDE进行开发,快乐编码!
//the loc and name variables are gathered from user input
String fileloc = loc +"/"+ name + ".java";
JavaCompiler jCompiler = ToolProvider.getSystemJavaCompiler();
List<String> options = Arrays.asList("-d", "./bin/",fileloc);
int compilationResult = jCompiler.run(null, null, null,
options.toArray(new String[options.size()]));
if (compilationResult == 0){
//This is the package name exported from selenium IDE exported files
File file = new File("./bin/com/example/tests/" + name);
URL url = null;
try {
url = file.toURL();
URL[] urls = {url};
ClassLoader cl = new URLClassLoader(urls);
org.junit.runner.Result result = JUnitCore.runClasses(cl.loadClass
("com.example.tests." + name));
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
};
} catch (MalformedURLException e) {
System.out.println("Error with file location (URL)");
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("Couldn't Not Find Test Class To Load");
e.printStackTrace();
}
}else{
System.out.println("Could not Find Java Source File Located in `" + fileloc + "`");
System.exit(1);
}
}