简体   繁体   English

Java:如何确定抽象类型的具体类型?

[英]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? 有什么方法可以返回与Set中传递的相同的具体类型? (Without having to return oldSet). (无需返回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. 如果oldSet是TreeSet,我也希望返回的集(newSet)是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. 仅当oldSet具体类具有不带参数的构造函数时,此方法才有效。

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. 那是假设MyClass是可克隆的。

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

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