java - 意外的未经检查的转换警告

标签 java generics

谁能解释为什么在 y 分配行上有一个未类型化的转换警告?请注意,x 或 z 分配没有警告。

public class Entity<T>
{
    @SuppressWarnings("unchecked")
    public <TX> Entity<TX> typed( Class<TX> type )
    {
        return (Entity<TX>) this;
    }

    @SuppressWarnings("unchecked")
    public static <TX> Entity<TX> typed( Entity<?> entity,  Class<TX> type )
    {
        return (Entity<TX>) entity;
    }

    public static void main( final String[] args )
    {
        final Entity<?> a = new Entity<Integer>();
        final Entity b = (Entity) a;

        final Entity<Integer> x = a.typed( Integer.class );
        final Entity<Integer> y = b.typed( Integer.class );
        final Entity<Integer> z = typed( b, Integer.class );
    }
}

最佳答案

b类型为 Entity ,这是一种原始类型。因此它的 API 看起来像这样:

public Entity typed(Class type)

所以你是从 Entity 转换过来的至 Entity<Integer> .编译器丢失了 type 之间的任何相关性参数和返回的实体类型,因此它无法进行任何检查。

换句话说,你可以使用:

final Entity<Integer> y = b.typed(String.class);

... 并且仍然只收到相同的警告。如果您尝试使用 x 进行相同的更改或 z ,你会得到一个编译时错误。

编辑:如评论中所述,您使用原始类型这一事实消除了所有泛型痕迹。

来自 JLS section 4.8 :

To facilitate interfacing with non-generic legacy code, it is possible to use as a type the erasure (§4.6) of a parameterized type (§4.5) or the erasure of an array type (§10.1) whose element type is a parameterized type. Such a type is called a raw type.

然后在section 4.6 :

Type erasure also maps the signature (§8.4.2) of a constructor or method to a signature that has no parameterized types or type variables. The erasure of a constructor or method signature s is a signature consisting of the same name as s and the erasures of all the formal parameter types given in s.

关于java - 意外的未经检查的转换警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16322536/

相关文章:

java - list 3.7 在实践中如何在 java 并发中工作?

java - 如何对直接在webapps下的资源请求应用过滤器

java - 运行时修改类路径——控制类加载顺序

java - 如何访问嵌套在另一个泛型中的泛型?

c# - 方法的类型推断,具有泛型和类继承

java - Selenium 'Unable to locate element'

java - mac中是否有快捷键可以为android中覆盖的方法生成javadoc?

java - 泛型中的编译类和运行时类

golang protobuf 无法在泛型类型中解码

java - 在 Java 中存储不同类型对象的有序列表的最佳方法?