[英]Java: How to determine the concrete type of an abstract type?
我有辦法
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;
}
有什么方法可以返回與Set中傳遞的相同的具體類型? (無需返回oldSet)。 不幸的是,不能克隆集合。
例
如果oldSet是TreeSet,我也希望返回的集(newSet)是TreeSet。
嘗試
Set<MyClass> doSomething(Set<MyClass> oldSet) {
Set<MyClass> newSet =oldSet.getClass().newInstance();
return newSet;
}
僅當oldSet具體類具有不帶參數的構造函數時,此方法才有效。
是的,使用反射:
Class<? extends Set<MyClass>> type = oldSet.getClass();
Constructor ctor = type.getConstructor();
Set<MyClass> newSet = ctor.newInstance();
(從我的頭開始,您必須添加幾個類型和大量的異常處理程序)。
您還可以克隆集合:
Class<? extends Set<MyClass>> type = oldSet.getClass();
Constructor ctor = type.getConstructor( Collection.class );
Set<MyClass> newSet = ctor.newInstance( oldSet );
您可以遍歷集合,克隆集合中的每個對象,然后將其放入新集合中。 那是假設MyClass是可克隆的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.