Steve Luke wrote:Look at the API for Class. It has methods for getting a particular Constructor, if you know its parameter types, and a method for getting an array of constructors which you can search through to find the best CTor for your task.
Once you have the correct Constructor, you can use one of its methods to create a new instance using the Constructor.
See if you can find the correct methods in the API, and let us know if you run into trouble.
Hi Steve, thank you for the quick reply. In order to get the correct constructor, I need to do this:
Constructor[] constructors = FileReader.class.getDeclaredConstructors();
for (int j=0; j<constructors.length; j++) {
Constructor constructor = constructors[j];
Class[] parameterTypes = constructor.getParameterTypes();
for (int i=0; i><parameterTypes.length; i++) {
Class c = parameterTypes[i];
System.out.println("Param type name = " + c.getName());
}
}
Now, .... this code is still not flexible enough to automatically go through the list of modules I am creating (FileReader, TextMapper ... etc).
Also, from the output of this code, I get:
Param type name = java.lang.String
So, this shows me the FileReader class expect a single parameter, which is a String, correct?
Now ... how do I access the
componentName which is a public String declared inside the FileReader Class if I want to compare it with a String obtained from a Configuration text file? i.e. if I have the following code:
if (componentValueFromConfigFile.equals(
FileReader.
componentName)) {
FileReader component = new
FileReader(componentKey);
componentClasses.put(componentKey, component);
}
Assuming we can somehow replace the
FileReader with something from the Constructor[] ?
Sorry ... I am new to this Dynamic coding ..... Am I getting this totally wrong? ....
Thank you very much and hope to hear from you soon.
Best regards,
Yong