简体   繁体   English

如何强制设置类型以创建通用实例?

[英]How to force set the type to create a generic instance?

How to force set the type to create a generic instance? 如何强制设置类型以创建通用实例?

public class MyClass<T extends MyClass2> { /* ... */ }

public class A extends MyClass2 { /* ... */ }

This should fail: 这应该失败:

MyClass myInstance = new MyClass();

And this should work: 这应该工作:

MyClass<A> myInstance = new MyClass<A>();

You can't do that in Java. 您无法在Java中做到这一点。 All generic classes have a corresponding raw type . 所有通用类都有对应的原始类型

If you happen to use Eclipse however, you can set it to produce a compile error for all uses of raw types: 但是,如果碰巧使用了Eclipse,则可以将其设置为对原始类型的所有使用产生编译错误:

Window -> Preferences -> Java / Compiler / Errors -> Generic Types -> Set "Usage of raw types" to Error. 窗口->首选项-> Java /编译器/错误->通用类型->将“原始类型的使用”设置为错误。

That's not possible. 那不可能 If you want a runtime check, your best bet is to provide a sole constructor which takes the type as argument. 如果要运行时检查,最好的选择是提供一个唯一的构造函数,该构造函数将类型作为参数。

public MyClass(Class<T> type) {
    this.type = type; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM