在java中扩展的通用方法 [英] Generic method with extend in java
本文介绍了在java中扩展的通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个通用方法的TestClass类。但是当我用这些参数运行
method1时,它执行得很好。
我错过了什么吗?应该method1抛出异常,因为对象不扩展Integer?
I have the class TestClass with a generic method. But when i run the method1 with those arguments it executes fine. Am i missing something? Should method1 throw exception because object does not extend Integer?
TestClass i = new TestClass();
i.method1(new Object(), new Integer(2));
public class TestClass {
protected final int testClassvar1=2;
public <E,T extends E> void method1(T t,E e) {
System.out.println(e.getClass());
}
}
推荐答案
强制约束T在编译时扩展E,当您调用需要指定将替换参数化类型的类型的方法时。
To enforce the constraint T extends E at compile time, when you call the method you need to specify the types that will replace the parameterized types. Otherwise, both types are assumed to be Object.
i.<Object,Integer>method1(new Object(), new Integer(2));
这篇关于在java中扩展的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文