Java泛型-类还是类&lt ;?扩展SomeClass> [英] Java Generics - Class or Class<? extends SomeClass>

查看:47
本文介绍了Java泛型-类还是类&lt ;?扩展SomeClass>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,该程序将使用Java反射(即 Class.forName())根据用户的输入动态创建类实例。一个要求是我的程序创建的实例必须扩展我定义的一个特定的类,称为 SomeClass 。我的问题是:要存储此类类型,是否应该使用有界的泛型 Class< ;?扩展SomeClass> 还是简单地无限制的泛型 Class ?我发现一些Java书籍说Class是使用无限制通配符泛型的良好实践之一,但是我想知道这是否适用于我程序中的情况。

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.

推荐答案

您应该使用 Class< ;?扩展SomeClass> ,因为这是泛型的用途。

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

在调用 Class.forName ,请检查它是否 SomeClass.class.isAssignableFrom 是新类。否则,您应该抛出 IllegalArgumentException ClassCastException

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.

编辑:或者,调用 asSubclass(SomeClass.class) 会为您完成此操作。

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

示例:

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

这篇关于Java泛型-类还是类&lt ;?扩展SomeClass&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆