Java generics + static factory methods = [panic]

I thought, I would understand Java generics by now. But now I'm helpless again. I have a generic class where a c-tor constructs correctly-typed instance, while a static factory method produces a type mismatch. Please look at the following code: public class _GenericFactoryMethods { public final static class DemoClass { private final T1 _1; private final T2 _2; // static factory method public static DemoClass create(T1 _1, T2 _2) { return new DemoClass(_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 _1 = str.getClass(); CharSequence _2 = str; // works DemoClass, CharSequence> dc1 = new DemoClass, CharSequence>(_1, _2); // compile error DemoClass, CharSequence> dc2 = DemoClass.create(_1, _2); } } The error is: Uncompilable source code - incompatible types required: _GenericFactoryMethods.DemoClass,java.lang.CharSequence> found: _GenericFactoryMethods.DemoClass,java.lang.CharSequence> Please help to understand and to solve this. *(I really need static factory methods for some of such classes).* **EDIT** Can someone also **explain why** explicit type parameters must be used?

以上就是Java generics + static factory methods = [panic]的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏