Java generics and collection purpose

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 do I do the runtime execution of an Object for type T?

+2


source to share


2 answers


Use this:

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

      



For more details see Class.

cast()

+6


source


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

      



+1


source







All Articles