How to call a method from a class given that I have the Constructor for it?

Viewed 128

If I have a constructor object Constructor<?> productConstructor, how can I call the run() method that exists in that class?

For example, let's say I have the class:

public class product1{
    public product1(Instances instance){
       // constructor
    }

    public void run(){
       // do something
    }
}

I can run the constructor for my class like this:

Constructor<?> productConstructor;
productConstructor = getProductConstructor(instance.getProductName());
// pass instance into constructor to run the tests
// example of what is happening here -> new product1(instance)
productConstructor.newInstance(new Object[] { instance });
public Constructor<?> getProductConstructor(String productName) {
    try {
        logger.info("Looking for Product Class: {}", productName);
        String fullQualifiedClassPath = "com.products." + productName;
        Class<?> clazz = Class.forName(fullQualifiedClassPath);
        return clazz.getConstructor(Instances.class);

    } catch (Exception e) {
        logger.error("Product: {} does not exist", productName);
    }
    return null;
}

If I keep the code as is, then I have to place the run() method inside of the constructor to run it, but I would like the run() method outside of the constructor. How can I call my run method using the Constructor class for my class?

For example, something like this is what I had in mind but doesn't work:

Constructor<?> productConstructor;
productConstructor = getProductConstructor(instance.getProductName());
productConstructor.newInstance(new Object[] { instance }).run(); // added .run() to the end but this doesn't work.

This doesn't work because run is undefined. This is because I cannot call a method this way on a class that is not known until runtime. This is where my problem lies.

2 Answers

The problem is productConstructor.newInstance(new Object[] { instance }); retrieves an Object and you have to cast it to the required type product1:

((product1)productConstructor.newInstance(new Object[] { instance })).run();

Let me offer you one of my projects reflection-utils.

<dependency>
    <groupId>ru.oleg-cherednik.utils.reflection</groupId>
    <artifactId>reflection-utils</artifactId>
    <version>1.0</version>
</dependency>
product1 product1 = ConstructorUtils.invokeConstructor(product1.class, Instances.class, new Instances());
product1.run();

In case you cannot include the file (e.g. file has package visibility), you can do the same using names:

String className = "com.products.product1";
Object product1 = ConstructorUtils.invokeConstructor(className, Instance.class, new Instance());

String methodName = "run";
MethodUtils.invokeMethod(product1, methodName);

You can find more examples of how to use reflection there.

I was able to do it like this:

Constructor<?> productConstructor;
Class<?> productClass;
productConstructor = getProductConstructor(instance.getProductName());
productClass = getProductClass(instance.getProductName());
productClass.getMethod("run").invoke(productConstructor.newInstance(new Object[] { instance }));

    public Constructor<?> getProductConstructor(String productName) {
        try {
            String fullQualifiedClassPath = "com.products." + productName;
            logger.info("Looking for Product Constructor: {}", fullQualifiedClassPath);
            Class<?> clazz = Class.forName(fullQualifiedClassPath);
            return clazz.getConstructor(Instances.class);

        } catch (Exception e) {
            logger.error("Product: {} does not exist", productName);
        }
        return null;
    }

    public Class<?> getProductClass(String productName) {
        try {
            String fullQualifiedClassPath = "com.products." + productName;
            logger.info("Looking for Product Class: {}", fullQualifiedClassPath);
            return Class.forName(fullQualifiedClassPath);

        } catch (Exception e) {
            logger.error("Product: {} does not exist", productName);
        }
        return null;
    }
Related