我见过如下所示的方法:
protected <T extends ABC> T save( T Acd, boolean en) {
Run Code Online (Sandbox Code Playgroud)
它有什么作用?在Java中调用的这些类型的方法声明是什么?
bas*_*sar 38
它被称为通用方法.这整个概念在Java中称为"泛型".该声明意味着T可以是ABC的子类的任何类型.
Okk*_*kky 15
有界类型参数:
有时您可能希望限制允许传递给类型参数的类型.例如,对数字进行操作的方法可能只想接受Number或其子类的实例.这是有界类型参数的用途.
要声明有界类型参数,请列出类型参数的名称,然后是extends关键字,后跟其上限.例:
下面的示例说明了扩展在一般意义上如何用于表示"扩展"(如在类中)或"实现"(如在接口中).此示例是返回三个Comparable对象中最大的对象的Generic方法:
public class MaximumTest
{
// determines the largest of three Comparable objects
public static <T extends Comparable<T>> T maximum(T x, T y, T z)
{
T max = x; // assume x is initially the largest
if ( y.compareTo( max ) > 0 ){
max = y; // y is the largest so far
}
if ( z.compareTo( max ) > 0 ){
max = z; // z is the largest now
}
return max; // returns the largest object
}
public static void main( String args[] )
{
System.out.printf( "Max of %d, %d and %d is %d\n\n",
3, 4, 5, maximum( 3, 4, 5 ) );
System.out.printf( "Maxm of %.1f,%.1f and %.1f is %.1f\n\n",
6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) );
System.out.printf( "Max of %s, %s and %s is %s\n","pear",
"apple", "orange", maximum( "pear", "apple", "orange" ) );
}
}
Run Code Online (Sandbox Code Playgroud)
protected <T extends ABC> T save( T Acd, boolean en) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
在这个函数中,有三个地方出现T了
<T extends ABC>TT Acd基于这些,我可以回答你的问题如下
它有什么作用?
save()是一种通用方法,它接受两个参数,其中一个参数的类型为T,并返回类型为 的值T。T是一个泛型类型,仅限于ABC. 的范围T仅限于save().
这些类型的方法声明在 Java 中被称为什么?
IMO,答案应该是有界类型参数,而不是泛型。有关Java 中泛型的更多信息,您可以在这里找到。
我想补充一个问题:为什么我们想要这样的东西?
有时您可能想要限制可用作参数化类型中的类型参数的类型。例如,对数字进行操作的方法可能只想接受 Number 或其子类的实例。这就是[1]的有界类型参数。
| 归档时间: |
|
| 查看次数: |
41581 次 |
| 最近记录: |