在泛型方法参数中键入T参数

Ami*_*itG 6 java generics

假设定义了以下类:

class Shape { }
class Circle extends Shape {  }
class Rectangle extends Shape { }  //  1
Run Code Online (Sandbox Code Playgroud)

您可以编写一个通用方法来绘制不同的形状:

public static <T extends Shape> void draw(T shape) { }   // 2
Run Code Online (Sandbox Code Playgroud)

Java编译器将T替换为Shape:

public static void draw(Shape shape) {  } // 3
Run Code Online (Sandbox Code Playgroud)

我的问题是,如果我们在类中直接定义// 3,那么我们仍然可以传递Shape,Circle并Rectangle在// 3处引用方法.那么为什么我们需要用类型参数来编写// 2泛型方法,<T extends Shape>这个方法与// 3完全相同?

您可以使用相同的示例来引用此链接:http://docs.oracle.com/javase/tutorial/java/generics/genMethods.html

das*_*ght 7

您可能需要也可能不需要它.如果您的方法必须处理T必须与其类型T extends Shape完全匹配的其他类型的对象,则需要它,例如:

public static <T extends Shape> void drawWithShadow(T shape, Class<T> shapeClass) {
    // The shadow must be the same shape as what's passed in
    T shadow = shapeClass.newInstance();
    // Set the shadow's properties to from the shape...
    shadow.draw(); // First, draw the shadow
    shape.draw();  // Now draw the shape on top of it
}
Run Code Online (Sandbox Code Playgroud)

在上面,传球Shape是不够的,因为我们无法制作完全相同类型的阴影.

如果没有这样的要求,简单Shape就足够了.