Java 如果在运行时多次编译类,则通过反射调用方法将返回不一致的结果
我在运行时编译一个类,然后调用该类的方法。如果类被编译多次,布尔方法总是返回true,而不是与参数相应的响应 奇怪的是,当我调试时,我可以看到编译的类是相同且正确的,在正确的类路径中找到了正确的方法,并且参数是相同的 编译代码的方法:Java 如果在运行时多次编译类,则通过反射调用方法将返回不一致的结果,java,reflection,Java,Reflection,我在运行时编译一个类,然后调用该类的方法。如果类被编译多次,布尔方法总是返回true,而不是与参数相应的响应 奇怪的是,当我调试时,我可以看到编译的类是相同且正确的,在正确的类路径中找到了正确的方法,并且参数是相同的 编译代码的方法: public static void compile(String conditionClass){ try { String fullPath = getClassPath() + "/" + target; File
public static void compile(String conditionClass){
try {
String fullPath = getClassPath() + "/" + target;
File file = new File(fullPath + ".java");
if (file.exists())
file.delete();
file.createNewFile();
PrintWriter pw = new PrintWriter(file);
pw.print(conditionClass);
pw.flush();
pw.close();
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
String[] methodArgs = {fullPath + ".java"};
javac.run(null, null, null, methodArgs);
targetClass = Class.forName(target);
file.delete();
} catch (Exception e){
e.printStackTrace();
}
}
public static String getClassPath() throws Exception {
for (String s : System.getProperty("java.class.path").split(":"))
if (s.indexOf("/target/classes") + "/target/classes".length() == s.length())
return s;
}
方法调用以下代码:
public boolean call(String methodName, String[][][] arg1, String[] arg2){
try {
Method m = targetClass.getMethod(methodName, new Class[]{String[][][].class, String[].class});
Object[] args = new Object[]{arg1, arg2};
Object response = m.invoke(null, args);
return (boolean)response;
} catch (Exception e){
e.printStackTrace();
}
return true;
}
正在编译的类的详细信息:
类主体,作为conditionClass传递:
public class TestClass{
public static boolean method1(String[][][] arg1, String[] arg2){
boolean res = true;
if(path[0][0][0].equals("test target"))
return false;
return res;
}
}
正如T.J.Crowder所建议的,问题是具有相同路径和名称的类不会再次加载
对于我的任务来说,简单地更改类的名称并将其重新加载到JVM就足够了,但这是一种crud方法,因此应该避免。类加载程序在加载类后缓存类(不会每次都从磁盘重新加载它们)。你在做什么来处理这件事吗?我没有看到任何看起来像它的代码,但这不是我真正涉足的领域……也许问题出在编译类中。因此,您打算编译/调用哪个类/方法会很有趣。请在更改之前和之后发布被编译的类^^。例如,请用一个示例演示您的问题,我们可以复制粘贴并运行该问题,以复制问题并帮助您解决问题。我怀疑第二个调用运行到异常中,导致您的方法返回true。然而,这意味着错误不在发布的代码中。因此,更新调用
调用的方式,最好发布整个程序。并通过异常重新刷新替换stacktrace打印。