I have a Java question. I have a configuration file that I read and extract some paths to java classes, let's say to an ArrayList of strings (for convenience I will call it path2libs).
I want to create an instance for every one of these classes dynamically by iterating this 'path2libs' array. I tried out something like this:
Class clazz = Class.forName("test.Demo");
Demo demo = (Demo) clazz.newInstance();
But I can't know what classes I will read, so I cannot do the appropriate casting.
When this is done, I want to call a method on each object (it is the same method in each case). All of these objects are based on an interface so I know their methods.
So, basically (to summarize) I have two questions :)
There are a number of issues.
First, Class#newInstance() expects the corresponding class to have a public constructor with an empty parameter list. You therefore have to make sure all the classes you want to work with have that. Otherwise, you'll need to get an appropriate Constructor, make it accessible, and provide the appropriate arguments.
Second, do you know the interface that all classes share at run time? If you do, you can cast all the instances to that interface type
InterfaceType interfaceInstance = (InterfaceType) clazz.newInstance();
interfaceInstance.interfaceMethod(/* arguments */);
If you don't, you'll have to again rely on reflection.
You'll need to retrieve the Method for the corresponding method, providing the types of each parameter in the method's parameter list.
Method method = clazz.getDeclaredMethod("methodName" /*, possible parameter list types */);
You can then invoke that method on your class' instance, again providing the appropriate arguments.
method.invoke(interfaceInstance /*, possible arguments */);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With