Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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();

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading