My purpose is to dynamically inject new attributes + getter setter methods to a class definition at runtime. Currently I have a method to regenerate the code with newly added attributes which then will compile the generated code.
Initially I'll have a template for each class at compile time. Upon running the project, the template class is loaded to runtime. I have written some code to dynamically generate java code and compile it. When I load the newly created class using the below code, I am not able to access injected methods. I think I am not able to overwrite existing runtime definition. I went through a lot of blogs but still couldn't understand why. Please help.
I am accessing the newly added methods in DROOLS and its not referenced in any other class which can raise issues during compilation. Rules of the rule engine with new attributes are updated at runtime and so I need to adapt my code accordingly. Below is the ClassLoader code. This code doesn't throw any exception but fails to solve my purpose. Not sure if coding is right.
public static boolean loadClass2RunTime() {
try {
File folder = new File("target");
File dir = new File(folder, "com/itap/template");
File[] classFiles = dir.listFiles();
URL[] url = new URL[] { folder.toURI().toURL() };
int i = 0;
for (File classFile : classFiles) {
if (classFile.getName().matches(".*\\.class")) {
System.out.println(classFile.getName().substring(0,
classFile.getName().lastIndexOf(".")));
ClassLoader loader = URLClassLoader
.newInstance(new URL[] { folder.toURI().toURL() });
Class cls = loader.loadClass("com.itap.template."
+ classFile.getName().substring(0,
classFile.getName().lastIndexOf(".")));
ClassLoader temp = cls.getClassLoader();
}
}
return true;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}