Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating objects in java, without knowing the Class at compile time

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 :)

  1. Create the desirable objects
  2. Call a method on each object
like image 853
Mario Avatar asked Dec 11 '25 06:12

Mario


1 Answers

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 */);
like image 72
Sotirios Delimanolis Avatar answered Dec 13 '25 19:12

Sotirios Delimanolis