Instantiate Java classes which implements specific Interface using reflection

血红的双手。 提交于 2019-12-12 16:11:02

问题


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?


回答1:


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



回答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




回答3:


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");
    }

}


来源:https://stackoverflow.com/questions/14680954/instantiate-java-classes-which-implements-specific-interface-using-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!