[英]Automatic type casting
我有一個程序需要接受類類型僅在運行時才知道的對象。 我想知道是否有可能讓程序自動將對象轉換回正確的類類型?
以下代碼是我目前擁有的; 我將逐步解釋我期望它做什么:
TryingSomething
實例,該實例添加兩個集合(一個是類類型Foo
,一個是類類型Bar
)。Foo
和Bar
)。 這會起作用嗎? 如果沒有,是否有替代方法可以讓我以正確的類類型檢索對象?感謝任何可以給我一些指示的人。
class TryingSomething<T> {
private Map<String, Set<T>> map = new HashMap<String, Set<T>>();
public void addCollection(Set<T> s, String name){
this.map.put(name, s);
}
public void test(){
Set<Foo> foo = new HashSet<Foo>();
Set<Bar> bar = new HashSet<Bar>();
addCollection(foo, "foo");
addCollection(bar, "bar");
}
public Set<T> getCollections(String name){
return this.map.get(name);
}
@SuppressWarnings("unchecked")
public static void main(String[] args){
TryingSomething t = new TryingSomething();
Set<Foo> foo = new HashSet<Foo>();
Set<Bar> bar = new HashSet<Bar>();
t.addCollection(foo, "foo");
t.addCollection(bar, "bar");
Set<Foo> fooList = t.getCollections("foo");
Set<Bar> barList = t.getCollections("bar");
}
}
class Foo{
}
class Bar{
}
您可以將類的類對象(運行時類型)用於映射鍵:
class TryingSomething {
private Map<Class<?>, Set<?>> map = new HashMap<>();
public <T> void addCollection(Set<T> s, Class<T> clazz){
map.put(clazz, s);
}
public void test(){
Set<Foo> foo = new HashSet<Foo>();
Set<Bar> bar = new HashSet<Bar>();
addCollection(foo, Foo.class);
addCollection(bar, Bar.class);
}
@SuppressWarnings("unchecked")
public <T> Set<T> getCollections(Class<T> clazz){
return (Set<T>)this.map.get(clazz);
}
public static void main(String[] args){
TryingSomething t = new TryingSomething();
Set<Foo> foo = new HashSet<Foo>();
Set<Bar> bar = new HashSet<Bar>();
t.addCollection(foo, Foo.class);
t.addCollection(bar, Bar.class);
Set<Foo> fooList = t.getCollections(Foo.class);
Set<Bar> barList = t.getCollections(Bar.class);
}
}
class Foo{
}
class Bar{
}
TryingSomething
類TryingSomething
應該是泛型的,因為您要存儲任意類型的集合(在運行時動態選擇)。 請注意,此實現根本不檢查插入的集合是否實際包含指定類型的對象(無論是在插入時還是在檢索時)——這里的責任在於此容器類的用戶。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.