barroco
barroco

Reputation: 3108

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

Upvotes: 1

Views: 818

Answers (2)

aioobe
aioobe

Reputation: 420951

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.

Upvotes: 2

BalusC
BalusC

Reputation: 1108692

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

Upvotes: 1

Related Questions