I am using dynamic execution but it tells me that the class is not found although I double checked the path and it's correct
This is the method I am using
public static void runIt(String fileToCompile) throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException, SecurityException, NoSuchMethodException
{System.out.println("Entered runIt()");
String r2="";
File file=File("/Users/apple/Documents/Documents/workspace/UserTesting/src/two.java");
System.out.println("The path of the file is "+fileToCompile);
System.out.println("HERE 1");
try
{
// Convert File to a URL
URL url = file.toURL(); // file:/classes/demo
URL[] urls = new URL[] { url };
System.out.println("HERE 2");
// Create a new class loader with the directory
ClassLoader loader = new URLClassLoader(urls);
System.out.println("HERE 3");
System.out.println("HERE 4");
Class<?> thisClass=null;
try{
thisClass = classLoader.loadClass("two");
}
catch(ClassNotFoundException e){
System.out.println("Class not found");
}
System.out.println("HERE 5");
Object newClassAInstance = thisClass.newInstance();
System.out.println("HERE 6");
Class params[] = new Class[1];
params[0]=String[].class;
Object paramsObj[] = {};
String m=null;
Object instance = thisClass.newInstance();
System.out.println("HERE 7");
Method thisMethod = thisClass.getDeclaredMethod("main", params);
System.out.println("HERE 8");
String methodParameter = "a quick brown fox";
// run the testAdd() method on the instance:
System.out.println((String)thisMethod.invoke(instance,(Object)m));
}
catch (MalformedURLException e)
{
}
}
This prints
HERE 1
HERE 2
HERE 3
HERE 4
Class not found
HERE 5
Is there anything missing in the method
You load a
.javafile by trying to load a class. First you must compile your.javainto a.classand only then load it. You can compile.javafile dynamically via the Java Compiler API.If you already have the source at compile time (you do not generate at run-time the content of two.java) you should call
Class.forName("two");instead ofclassLoader.loadClass("two").