Java generics + static factory methods = [panic]

I thought I would already understand Java generics. But now I'm helpless again.

I have a generic class where c-tor builds a properly typed instance, while the static factory method creates a type mismatch.

Take a look at the following code:

public class _GenericFactoryMethods { public final static class DemoClass<T1, T2> { private final T1 _1; private final T2 _2; // static factory method public static <T1, T2> DemoClass<T1, T2> create(T1 _1, T2 _2) { return new DemoClass<T1, T2>(_1, _2); } // usual c-tor public DemoClass(T1 _1, T2 _2) { this._1 = _1; this._2 = _2; } public T1 get1() { return _1; } public T2 get2() { return _2; } } public void doSomething() { String str = "test"; Class<? extends CharSequence> _1 = str.getClass(); CharSequence _2 = str; // works DemoClass<Class<? extends CharSequence>, CharSequence> dc1 = new DemoClass<Class<? extends CharSequence>, CharSequence>(_1, _2); // compile error DemoClass<Class<? extends CharSequence>, CharSequence> dc2 = DemoClass.create(_1, _2); } } 

Error:

 Uncompilable source code - incompatible types required: _GenericFactoryMethods.DemoClass<java.lang.Class<? extends java.lang.CharSequence>,java.lang.CharSequence> found: _GenericFactoryMethods.DemoClass<java.lang.Class<capture#794 of ? extends java.lang.CharSequence>,java.lang.CharSequence> 

Please help to understand and solve this.
(I really need static factory methods for some of these classes).

EDIT
Can someone else explain why explicit type parameters should be used

+4
source share
2 answers

Try

 DemoClass.<Type1, Type2>create(_1, _2); 

As I recall from Josh Bloch's presentation, Effective Java 2nd Edition: "God kills a kitten every time you specify an explicit type parameter." Try to avoid such designs.

+6
source

In this case, you need to explicitly set the generic type:

 dc2 = DemoClass.<Class<? extends CharSequence>, CharSequence>create(_1, _2); 
+1
source

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


All Articles