如何创建根据 T 采取不同行为的通用方法?
How to create generic method that acts differently depending on the T?
在不使用 if 语句检查类型的情况下,创建一个根据给定类型采取不同行为的泛型方法的最佳方法是什么?
例如,如何创建一个 Add<T>(T x, T y)
方法 returns x + y
if T
is Integer
and x.add(y)
if T
是 BigInteger
,没有检查 T
的 class 是否是 BigInteger
。
泛型类型参数没有这样的功能。
您可能正在寻找 方法重载:Java 允许您创建多个具有相同名称的方法,只要它们具有不同的参数类型(and/or 不同数量的参数)。所以你可以写两个或多个具有不同实现的方法,如下所示:
public Integer add(Integer i, Integer j) {
// do stuff
}
public BigInteger add(BigInteger i, BigInteger j) {
// do other stuff
}
当您调用 add
时,编译器将通过检查您传递的参数类型来决定选择哪些方法。
在不使用 if 语句检查类型的情况下,创建一个根据给定类型采取不同行为的泛型方法的最佳方法是什么?
例如,如何创建一个 Add<T>(T x, T y)
方法 returns x + y
if T
is Integer
and x.add(y)
if T
是 BigInteger
,没有检查 T
的 class 是否是 BigInteger
。
泛型类型参数没有这样的功能。
您可能正在寻找 方法重载:Java 允许您创建多个具有相同名称的方法,只要它们具有不同的参数类型(and/or 不同数量的参数)。所以你可以写两个或多个具有不同实现的方法,如下所示:
public Integer add(Integer i, Integer j) {
// do stuff
}
public BigInteger add(BigInteger i, BigInteger j) {
// do other stuff
}
当您调用 add
时,编译器将通过检查您传递的参数类型来决定选择哪些方法。