Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

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

843793Apr 22 2010 — edited Apr 23 2010
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

Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on May 21 2010
Added on Apr 22 2010
3 comments
171 views