Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate Java classes which implements specific Interface using reflection

I am new to Reflection. I have seen some of the questions and tutorials.

Let's assume I have one interface which's implemented by 3 classes A,B,C

public interface MyInterface {
doJob();

}

Now using reflection I want to invoke each class

Class<?> processor = Class.forName("com.foo.A");
Object myclass = processor.newInstance();

Rather than creating an Object, can't I restrict the whole process to specific type. I want to invoke only MyInterface type classes.

If I pass com.foo.A it should create A class object, com.foo.B should do B class Object, but if I pass some com.foo.D who exists but still doesn't implement MyInterface shouldn't be invoked.

How can I achieve this?

like image 996
RaceBase Avatar asked Feb 24 '26 18:02

RaceBase


1 Answers

try

MyInterface newInstance(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    Class<?> cls = Class.forName(className);
    if (!MyInterface.class.isAssignableFrom(cls)) {
        throw new IllegalArgumentException();
    }
    return (MyInterface) cls.newInstance();
}
like image 107
Evgeniy Dorofeev Avatar answered Feb 26 '26 09:02

Evgeniy Dorofeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!