简体   繁体   中英

Java: How to determine the concrete type of an abstract type?

I have a method

public static Set<MyClass> doSomething(Set<MyClass> oldSet) {

  //I don't necessarily want this to be a HashSet
  Set<MyClass> newSet = new HashSet<MyClass>();

  //Add some things to newSet

  return newSet;
}

Is there any way that I can return the same concrete type as the passed in Set? (Without having to return oldSet). Unfortunately, Sets can't be cloned.

Example

if oldSet is a TreeSet, I would also like the returned set (newSet) to be a TreeSet.

try

Set<MyClass> doSomething(Set<MyClass> oldSet) {

  Set<MyClass> newSet =oldSet.getClass().newInstance();

  return newSet;
}

This only works if concrete class of oldSet has a constructor without parameters.

Yes, using reflection:

Class<? extends Set<MyClass>> type = oldSet.getClass();
Constructor ctor = type.getConstructor();
Set<MyClass> newSet = ctor.newInstance();

(from the top of my head, you'll have to add a couple of types and a ton of exception handlers).

You can also clone the set:

Class<? extends Set<MyClass>> type = oldSet.getClass();
Constructor ctor = type.getConstructor( Collection.class );
Set<MyClass> newSet = ctor.newInstance( oldSet );

You can go over the set, clone each object in the set and put it into the new set. That is assuming that MyClass is clone-able.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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