gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:48:47 25 4
gpt4 key购买 nike

谁能解释为什么在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com