I have the class name stored in a property file. I know that the classes store will implement IDynamicLoad. How do I instantiate the class dynamically?
Right now I have
Properties foo = new Properties();
foo.load(new FileInputStream(new File("ClassName.properties")));
String class_name = foo.getProperty("class","DefaultClass");
//IDynamicLoad newClass = Class.forName(class_name).newInstance();
Does the newInstance only load compiled .class files? How do I load a Java Class that is not compiled?
You need to compile it first. This can be done programmatically with the
javax.toolsAPI. This only requires the JDK being installed at the local machine on top of JRE.Here’s a basic kickoff example (leaving obvious exception handling aside):
Which yields like
Further use would be more easy if those classes
implementsa certain interface which is already in the classpath.Otherwise you need to involve the Reflection API to access and invoke the (unknown) methods/fields.
That said and unrelated to the actual problem:
Letting
java.io.Filerely on current working directory is recipe for portability trouble. Don’t do that. Put that file in classpath and useClassLoader#getResourceAsStream()with a classpath-relative path.