Forum Stats

  • 3,769,456 Users
  • 2,252,967 Discussions
  • 7,875,032 Comments

Discussions

Return an object of the same type as method's parameter

843793
843793 Member Posts: 41,732 Green Ribbon
edited Apr 23, 2010 12:08PM in Generics
Hi,

Is it possible to do something like that?
public <T, E> T<E> method(T<E> arg) {    
    T<E> copy = arg.getClass().newInstance();
    return copy;
}
The method should create and return generic object on the basis of parameter's type. I would like to operate on Collection<E> without worrying about actual type of collection (List, Set...).

method(new ArrayList<Something>) should return ArrayList<Something>
method(new HashSet<Something>) should return HashSet<Something>
and so on.

Cheers

Comments

  • DrClap
    DrClap Member Posts: 25,479
    Sure, that will work as long as the type in question has an accessible zero-argument constructor. So yes, in your example you could return a new ArrayList or a new HashSet. Not a new ArrayList<Thing>, though, because generics are a compile-time concept only and mean nothing at run time.

    By the way it's more traditional to just pass a Class object directly, instead of a wasted object of that class:
    public Class<?> method(Class<?> arg) {    
        Class<?> copy = arg.newInstance();
        return copy;
    }
    And to call that:
    ArrayList result = method(ArrayList.class);
  • 843793
    843793 Member Posts: 41,732 Green Ribbon
    @DrClap: shouldn't your method be:
    public Object method(Class<?> arg) {    
        Object copy = arg.newInstance();
        return copy;
    }
  • DrClap
    DrClap Member Posts: 25,479
    Robert.Bossy wrote:
    @DrClap: shouldn't your method be:
    public Object method(Class<?> arg) {    
    Object copy = arg.newInstance();
    return copy;
    }
    Yes, you're right. Or perhaps something like
    public T method(Class<? extends T> arg) {    
        T copy = arg.newInstance();
        return copy;
    }
    Although I have to say, this method doesn't look as useful to me as it apparently did to the OP.
This discussion has been closed.