The Java™ Tutorials — Generics :Erasure of Generic Methods 泛型方法的类型擦除

本文详细阐述了Java泛型方法在编译阶段如何进行类型擦除,以及这一特性如何影响泛型类的使用。通过具体实例展示了如何在不同类中应用泛型方法,并解释了编译器在类型参数处理上的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The Java™ Tutorials — Generics :Erasure of Generic Methods 泛型方法的类型擦除

原文地址:https://docs.oracle.com/javase/tutorial/java/generics/genMethods.html

关键点

  • 消除方法:同对泛型类的处理 
    • 无限制:替换为Object
    • 有限制:替换为第一受限类型

全文翻译

The Java compiler also erases type parameters in generic method arguments. Consider the following generic method:

Java编译器也会消除在泛型方法中的类型参数。看下面的泛型方法:

// Counts the number of occurrences of elem in anArray.
//
public static <T> int count(T[] anArray, T elem) {
int cnt = 0;
for (T e : anArray)
if (e.equals(elem))
++cnt;
return cnt;
}

Because T is unbounded, the Java compiler replaces it with Object:

由于T是不受限制的,Java编译器就会将其替换为Object:

public static int count(Object[] anArray, Object elem) {
int cnt = 0;
for (Object e : anArray)
if (e.equals(elem))
++cnt;
return cnt;
}

Suppose the following classes are defined:

假设我们定义了如下的几个类:

class Shape { /* ... */ }
class Circle extends Shape { /* ... */ }
class Rectangle extends Shape { /* ... */ }

You can write a generic method to draw different shapes:

你可以写一个泛型方法画出不同的形状:

public static <T extends Shape> void draw(T shape) { /* ... */ }

The Java compiler replaces T with Shape:

Java 编译器就会把T替换为Shape:

public static void draw(Shape shape) { /* ... */ }

_

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值