java泛型和集合赋值

时间:2009-09-29 14:45:52

标签: java generics collections

如果我有这门课程:

class Foo<T> implements SomeInterface
{
    final private List<T> list = new ArrayList<T>();
    final private Class<? extends T> runtimeClass;

    public Foo(Class<? extends T> cl) { this.runtimeClass = cl; }

    // method override from SomeInterface
    @Override public boolean addChild(Object o)   
    {
        // Only add to list if the object is an acceptible type.
        if (this.runtimeClass.isInstance(o))
        {
            list.add( /* ??? how do we cast o to type T??? */ );
        }
    }

    public List<T> getList() 
    { 
        return this.list; 
    } // yes, I know, this isn't safe publishing....
}

如何从Object执行运行时强制转换以键入T?

2 个答案:

答案 0 :(得分:6)

使用此:

list.add(this.runtimeClass.cast(o))

有关详细信息,请参阅Class. cast()

答案 1 :(得分:1)

// method override from SomeInterface    
@Override public boolean addChild(Object o)       
{        
     // Only add to list if the object is an acceptible type.        
     if (this.runtimeClass.isInstance(o))        
     {            
         list.add((T)o);        
     }    
}
相关问题