简体   繁体   中英

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. 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:

Window -> Preferences -> Java / Compiler / Errors -> Generic Types -> Set "Usage of raw types" to Error.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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