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