简体   繁体   English

Java泛型和集合分配

[英]java generics and collection assignment

If I have this class: 如果我有这堂课:

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....
}

how would I perform a runtime cast from Object to type T? 如何执行从Object到T类型的运行时转换?

Use this: 用这个:

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

See Class. 请参阅Class. cast() for details 详情请参阅cast()

// 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);        
     }    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM