何时是类型擦除后输入的函数的泛型返回值?

时间:2016-01-02 03:54:48

标签: java generics type-erasure

此问题由this StackOverflow question about unsafe casts: Java Casting method without knowing what to cast to引入。在回答我遇到此问题的问题时,我无法根据纯粹的规范

进行解释

我在The Java Tutorials中找到了以下语句 Oracle文档:

  

没有解释“必要时”的确切含义,以及 我在Java Language Specification中发现没有提及这些演员阵容,所以我开始尝试。

让我们看看以下代码:

// Java source
public static <T> T identity(T x) {
    return x;
}
public static void main(String args[]) {
    String a = identity("foo");
    System.out.println(a.getClass().getName());
    // Prints 'java.lang.String'

    Object b = identity("foo");
    System.out.println(b.getClass().getName());
    // Prints 'java.lang.String'
}

使用javac编译并使用the Java Decompiler反编译:

// Decompiled code
public static void main(String[] paramArrayOfString)
{
    // The compiler inserted a cast to String to ensure type safety
    String str = (String)identity("foo");
    System.out.println(str.getClass().getName());

    // The compiler omitted the cast, as it is not needed
    // in terms of runtime type safety, but it actually could
    // do an additional check. Is it some kind of optimization
    // to decrease overhead? Where is this behaviour specified?
    Object localObject1 = identity("foo");
    System.out.println(localObject1.getClass().getName());
}

我可以看到在第一种情况下有一个确保类型安全的演员, 但在第二种情况下,它被省略。它是 很好,因为我想将返回值存储在Object中 类型变量,因此根据类型安全性,强制转换不是必需的。然而,它导致了一个有趣的行为与不安全的演员表:

public class Erasure {
    public static <T> T unsafeIdentity(Object x) {
        return (T) x;
    }

    public static void main(String args[]) {
        // I would expect c to be either an Integer after this
        // call, or a ClassCastException to be thrown when the
        // return value is not Integer
        Object c = Erasure.<Integer>unsafeIdentity("foo");
        System.out.println(c.getClass().getName());
        // but Prints 'java.lang.String'
    }
}

编译和反编译,我看到没有类型转换以确保在运行时正确的返回类型:

// The type of the return value of unsafeIdentity is not checked,
// just as in the second example.
Object localObject2 = unsafeIdentity("foo");
System.out.println(localObject2.getClass().getName());

这意味着如果泛型函数应该返回给定的对象 类型,不保证最终返回该类型。一个 使用上述代码的应用程序将在尝试的第一个点失败 如果它完全如此,则将返回值转换为Integer,所以我觉得 它打破了fail-fast principle

在此过程中插入此强制转换的编译器的确切规则是什么? 确保类型安全的编译以及指定的规则在哪里?

修改

我看到编译器不会深入研究代码并试图证明通用代码确实返回它应该的内容,但是它可以插入一个断言,或者至少是一个类型转换(它在特定情况下已经做过,如第一个例子所示)确保正确的返回类型,因此后者会抛出ClassCastException

// It could compile to this, throwing ClassCastException:
Object localObject2 = (Integer)unsafeIdentity("foo");

3 个答案:

答案 0 :(得分:4)

如果你在规范中找不到它,那意味着它没有被指定,只要擦除的代码满足,由编译器实现来决定是否插入强制转换。非通用代码的类型安全规则。

在这种情况下,编译器的擦除代码如下所示:

public static Object identity(Object x) {
    return x;
}
public static void main(String args[]) {
    String a = (String)identity("foo");
    System.out.println(a.getClass().getName());

    Object b = identity("foo");
    System.out.println(b.getClass().getName());
}

在第一种情况下,在删除的代码中需要强制转换,因为如果删除它,则删除的代码将无法编译。这是因为Java保证在reifiable类型的引用变量中运行时保存的内容必须是instanceOf可再生类型,因此这里需要进行运行时检查。

在第二种情况下,擦除的代码在没有强制转换的情况下编译。是的,如果您添加了演员表,它也会编译。所以编译器可以决定哪种方式。在这种情况下,编译器决定不插入强制转换。这是一个完全有效的选择。你不应该依赖编译器来决定。

答案 1 :(得分:-1)

版本1是首选,因为它在compiletime失败。

Typesafe版本1非遗留代码:

http.js

Typesafe版本2旧版代码(A run-time type error [...] In an automatically generated cast introduced to ensure the validity of an operation on a non-reifiable typereference type casting):

angular2.js

TypeSafe版本3遗留代码,每次都知道超类型的方法(JLS The erasure of a type variable (§4.4) is the erasure of its leftmost bound.):

private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        if (e.Key == VirtualKey.Enter)
        {
            additem_button.Focus(FocusState.Pointer);
        }
    }
//FocusState.Pointer as if the button was clicked by the user..

对象仅用于说明Object是版本1和版本3中的有效分配目标,但如果可能,您应该使用实际类型或泛型类型。

如果你使用另一个版本的java,你应该查看规范的特定页面,我不希望有任何变化。

答案 2 :(得分:-1)

我无法解释得很清楚,但评论不能添加我想要的代码,所以我添加了这个答案。希望这个答案可以帮助你理解。评论不能添加我想要的代码。

在您的代码中:

public class Erasure {
    public static <T> T unsafeIdentity(Object x) {
        return (T) x;
    }

    public static void main(String args[]) {
        // I would expect it to fail:
        Object c = Erasure.<Integer>unsafeIdentity("foo");
        System.out.println(c.getClass().getName());
        // but Prints 'java.lang.String'
    }
}

它将在编译后擦除泛型。在编译时,Erasure.unsafeIdentity没有错误。 jvm擦除泛型依赖于你给出的泛型参数(整数)。之后,功能就像这样?:

public static Integer unsafeIdentity(Object x) {
    return x;
}

事实上,协变回报将添加Bridge Methods

public static Object unsafeIdentity(Object x) {
    return x;
}

如果该函数与上一个函数类似,您认为main方法中的代码编译失败吗?它没有错误。泛型Erasure不会在这个函数中添加强制转换,而返回参数不是java函数的缩进。

我的解释有点牵强,但希望可以帮助你理解。

编辑:

关于该主题的谷歌之后,我猜你的问题是使用桥接方法的协变返回类型。 BridgeMethods

相关问题