任何人都可以解釋爲什麼在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'在從'a'強制轉換後是無類型的,因此當您使用'b.typed(Integer.class)''將其轉換回來時,它是無類型的。泛型類型不同於類類型;他們不被保留,當「失敗」。 – Vulcan 2013-05-01 16:53:31