原始类型成员丢失的泛型类型 [英] Generic type lost for member of raw type

查看:92
本文介绍了原始类型成员丢失的泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在这个类中 Foo< T> ,我发现了一个奇怪的行为, 字符串成员与 T 没有任何关系:

  package test; 
import java.util.ArrayList;

public class Foo< T> {
ArrayList< String>串;

T getSome(){
return null;




$ b $ p
$ b

该类用于main:

  package test; 

public class Main {

public static void main(){
Foo< Integer> intFoo = new Foo<>();
Integer i = intFoo.getSome();
String s1 = intFoo.strings.get(0);

Foo rawFoo = new Foo();
Object o = rawFoo.getSome();
String s2 = rawFoo.strings.get(0); //这一行的编译错误
}
}

编译错误是不兼容的类型。required:String found:Object。



看来Java忘记了 String 类型参数为 ArrayList 当使用 Foo 的原始类型时。



我的java版本是1.7.0_21

解决方案

简单地说,因为 rawFoo 是非常原始的,它的非静态成员也变得生。

概述于 JLS§4.8


更确切地说,原始类型被定义为以下之一:


  • 通过使用不带伴随类型参数列表的泛型类型声明的名称形成的引用类型。

  • 元素类型为原始类型的数组类型。




$ b原始类型R的静态成员类型,它不从R的超类或超接口继承。 $ b

记下最后一个项目符号。


I have found a strange behavior when working with generics.

In this class Foo<T>, the strings member doesn't have anything to do with T:

package test;
import java.util.ArrayList;

public class Foo<T> {
    ArrayList<String> strings;

    T getSome() {
        return null;
    }
}

The class is used in main:

package test;

public class Main {

    public static void main() {
        Foo<Integer> intFoo = new Foo<>();
        Integer i = intFoo.getSome();
        String s1 = intFoo.strings.get(0);

        Foo rawFoo = new Foo();
        Object o = rawFoo.getSome();
        String s2 = rawFoo.strings.get(0); // Compilation error on this line
    }
}

The compilation error is "incompatible types. required: String found: Object".

It appears that Java forgets the String type argument to ArrayList when raw type of Foo is used.

My java version is 1.7.0_21

解决方案

Simply put, because rawFoo is raw, its non-static members also become raw.

This is outlined in JLS §4.8:

More precisely, a raw type is defined to be one of:

  • The reference type that is formed by taking the name of a generic type declaration without an accompanying type argument list.

  • An array type whose element type is a raw type.

  • A non-static member type of a raw type R that is not inherited from a superclass or superinterface of R.

Note the last bullet.

这篇关于原始类型成员丢失的泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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