3

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?

RaceBase
  • 18,428
  • 47
  • 141
  • 202
  • 1
    check this link ...... http://stackoverflow.com/questions/492184/how-do-you-find-all-subclasses-of-a-given-class-in-java – sunleo Feb 04 '13 at 05:42

3 Answers3

6

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();
}
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
2

Well, Java Reflection is a general purpose mechanism, so if you use only the code you've presented in the question, there is no way to achieve what you want to achieve. Its exactly like asking how to restrict Java of create objects of types others than those implementing 'MyInterface'. Java's 'new' is general purpose and it will allow to create any object you want.

In general you can write your own code for this. And instead of calling directly

Class.forName

Call your own code

You can implement something like that in compile time/run time.

Example for Compile type check (you'll need a Class object created):

public T newInstance(Class<T extends MyInterface cl) {
  return cl.newInstance();
}  

Example for runtime was posted by Evgeniy Dorofeev already

Hope this helps

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
0

try below code

 package com.rais.test;

public class Client {

    public static void main(String[] args) {
        try {
            System.out.println(createObject("com.rais.test.A"));
            System.out.println(createObject("com.rais.test.D"));

        } catch (Exception e) {
            e.printStackTrace();
        }
}

public static MyInterface createObject(String className)
        throws ClassNotFoundException, InstantiationException,
        IllegalAccessException {

    Class<?> clazz = Class.forName(className);

    if (MyInterface.class.isAssignableFrom(clazz)) {
        return (MyInterface) clazz.newInstance();

    } else {

        throw new RuntimeException(
                "Invalid class: class should be child of MyInterface");
    }

}
Rais Alam
  • 6,970
  • 12
  • 53
  • 84