从泛型超类型扩展? [英] Extend from Generic Supertype?

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

问题描述

在 Java 中,我可以从泛型超类型进行扩展吗?根据这篇文章,看起来我应该能够:http://www.ibm.com/developerworks/java/library/j-djc05133.html.

In Java, am I able to extend from a generic supertype? According to this article, it looks like I should be able to: http://www.ibm.com/developerworks/java/library/j-djc05133.html.

public abstract class MyClass<T> extends T {

但是,当我在应用程序中执行类似操作时,出现以下错误:无法将类型参数 T 引用为超类型."

However, when I do something similar in my application, I get the following error: "Cannot refer to the type parameter T as a supertype."

有谁知道我是否能够从 Java 中的泛型超类型进行扩展?如果是这样,是否需要特殊的东西来实现这一点?

Does anyone know if I am able to extend from a generic supertype in Java? And, if so, is there something special needed to make this happen?

我读错了文章.它实际上是在讨论这个潜在的问题.

推荐答案

可以从具有泛型类型参数的超类型继承.例如:

You are able to inherit from a supertype that has generic type parameters. For instance:

public class MyList<T> extends AbstractList<T>

(甚至给参数边界,例如):

(or even give the parameters bounds, e.g.):

public class MyStringList extends AbstractList<String>

不能定义具有通配符超类型的类.这样的概念在 Java 中没有任何意义(而且我不相信它在抽象上有多大价值).在您的 MonitoredDevice 示例中,我什至不确定您期望的功能是什么.

You are not able to define a class that has a wildcard supertype. Such a concept doesn't make any sense in Java (and I'm not convinced it has much value in the abstract). In your MonitoredDevice example, I'm not even sure what functionality you expect there.

由于擦除,这在 Java 工作方式的基本层面上是不可能的.每个类都必须有一个超类 - MonitoredDevice 的超类是什么?MonitoredDevice 对象有哪些可用的方法?您将无法在此类上调用任何继承的方法,因为编译器无法保证此类方法存在,字节码也无法表示此类调用.

Because of erasure this is simply not possible at a fundamental level of the way Java works. Each class must have a superclass - what is the superclass of MonitoredDevice? What methods are available on a MonitoredDevice object? You wouldn't be able to call any inherited methods on this class as the compiler could not guarantee such methods exist, nor could the bytecode represent such calls.

我怀疑使用 动态代理.

好的,在完整阅读这篇文章后,我可以看出这种声明背后的动机是什么.但是在完整阅读文章后,您也会意识到目前 Java 不支持此功能.根本原因是因为擦除;在当前的机制下,这种技术永远不可能实现,本文详细介绍了具体是什么阻止了它的工作.

OK, after reading the article fully I can see what the motivation behind such a declaration would be. But after reading the article fully, you also realise that this isn't supported by Java at present. The fundamental reason why is due to erasure; such a technique would never be possible under the current mechanics, and the article goes into a lot more detail of what specifically prevents this from working.

这篇关于从泛型超类型扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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