如果您需要将接口(interface)类型的参数传递给您可以使用两个 impl 的方法。
使用有界类型参数:
public static <I extends InterfaceObj> void isTrue(boolean expression, I interfaceobj) {
if(!expression){
throw new RunTimeException(interfaceobj);
}}
否则你可以使用接口(interface)类型:
public static void isTrue(boolean expression, InterfaceObj interfaceobj) {
if(!expression){
throw new RunTimeException(interfaceobj);
}
}
然后,如果我有一个实现 InterfaceObj 的类,我可以在第一个和第二个示例中使用它,这样我就看不出它们之间的区别、优点和缺点。
- 每种情况有什么区别?
- 什么时候使用一种或另一种更好?
最佳答案
I don't see the difference, advantadges and disadvantages from one or other.
我想你忘记了 Collection !
如果您有一个 Collection 参数,这就是有界类型参数的真正优势发挥作用的地方
在这个方法中,你只能传递一个像List<InterfaceObj> list = new ArrayList<InterfaceObj>();
这样实例化的列表。
public static void processList(List<InterfaceObj> input){
//...
}
但是如果您使用有界参数化泛型,您可以将以下所有列表作为输入传递
List<InterfaceObj> list = new ArrayList<InterfaceObj>();
List<SubInterfaceObj> list = new ArrayList<SubInterfaceObj>();
List<SubSubInterfaceObj> list = new ArrayList<SubSubInterfaceObj>();
public static void processList(List<? extends InterfaceObj> input){
//...
}
关于java - 当使用 Bounded 类型参数或直接类型接口(interface)时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38914132/