Java Generics - Class or Class<? extends SomeClass>

我的未来我决定 提交于 2019-12-30 06:06:46

问题


I am writing a program which will use Java reflection (i.e., Class.forName()) to dynamically create class instance based on user's input. One requirement is that the instance my program creates must extend one specific Class I defined, called it SomeClass. My question is: for storing this class type, should I use bounded generic, Class<? extends SomeClass>, or simply unbounded generic, Class? I found some Java books say that Class is one of the good practices for using unbounded wildcard generic, but I am wondering whether this apply to the situation in my program.

Please feel free to let me know if you found my question is not clear enough or some information is needed.


回答1:


You should use Class<? extends SomeClass> because that's what generics are for.

At the time when you invoke Class.forName, check to see if it SomeClass.class.isAssignableFrom the new class. Otherwise, you should throw an IllegalArgumentException or ClassCastException.

EDIT: Alternatively, calling asSubclass(SomeClass.class) will do this for you.

For example:

public SomeClass instantiate(String name)
  throws ClassNotFoundException, InstantiationException, IllegalAccessException {

    Class<?> raw = Class.forName(name);

    //throws ClassCastException if wrong
    Class<? extends SomeClass> generic = raw.asSubclass(SomeClass.class);

    // do what you want with `generic`

    return generic.newInstance();
}


来源:https://stackoverflow.com/questions/16969952/java-generics-class-or-class-extends-someclass

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