Java中的类型擦除和重载:为什么这样做? [英] Type Erasure and Overloading in Java: Why does this work?

查看:101
本文介绍了Java中的类型擦除和重载:为什么这样做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

public class Pair< T, U > {
    public T first;
    public U second;
}
public class Test {
    public int method( Pair< Integer, Integer > pair ) {
        return 0;
    }
    public double method( Pair< Double, Double > pair ) {
        return 1.0;
    }
}

这实际上是按照预期编译和工作的。但是如果返回类型相同,则不会编译,预期的名称冲突:方法(对)和方法(对)具有相同的擦除

This actually compiles and works like one would expect. But if the return types are made to be the same, this doesn't compile, with the expected "name clash: method(Pair) and method(Pair) have the same erasure"

鉴于返回类型不是方法签名的一部分,这种重载怎么可能?

Given that the return type isn't part of the method signature, how is this overloading possible?

推荐答案

考虑以下4种方法

           Java code                        bytecode

m1:    Byte f(List<Byte> list)           f List -> Byte
m2:    Long f(List<Byte> list)           f List -> Long
m3:    Byte f(List<Long> list)           f List -> Byte
m4:    Long f(List<Long> list)           f List -> Long

根据当前的Java语言规范,

According to the current Java Language Spec,


  • m1和m2不能共存,m3和m4也不能共存。因为它们具有相同的参数类型。

  • m1 and m2 cannot coexist, nor can m3 and m4. because they have the same parameter types.

m1和m3可以共存,m1和m4也可以共存。因为它们有不同的参数类型。

m1 and m3 can coexist, so can m1 and m4. because they have different parameter types.

但是javac 6只允许m1 + m4,而不是m1 + m3。这与方法的字节码表示有关,包括返回类型。因此,m1 + m4是可以的,但不是m1 + m3。

But javac 6 only allows m1+m4, not m1+m3. That's related to the bytecode representation of methods, which includes return types. Therefore, m1+m4 are ok, but not m1+m3.

这是Java和JVM规范看不到的混乱。 javac没有正确的方式。

This is a screwup where Java and JVM specs don't see eye to eye. There is no "correct" way for javac.

虽然很糟糕,但好消息是,重载是一种虚荣,而不是必需品。我们总是可以为这些方法使用不同的,更具描述性和不同的名称。

While it sucks, the good news is, overloading is a vanity, not a necessity. We can always use different, more descriptive and distinct names for these methods.

这篇关于Java中的类型擦除和重载:为什么这样做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆