[英]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.