Default generic type

Let's say I have the following general class:

public class Foo<T extends Bar> { // stuff } 

Is it possible to specify a default type (e.g. Baz ) that will act like T if there was no T in?

+4
source share
2 answers

No. See "Type Variables" in the Java Language Specification.

However, you can provide subclasses that achieve a similar goal:

 public class Foo<T extends Bar> { ... } public class FooDefault extends Foo< Baz > { ... } 
+3
source

Use factory method e.g.

 public <T extends Bar> static Foo<T> getInstance(Class<T> clz) { if (clz == null) return new Foo<Bar>; else return clz.newInstance(); } 
+2
source

Source: https://habr.com/ru/post/1388518/


All Articles