[英]Automatic type casting
I have a program that needs to accept objects of which the class types are only known at runtime.我有一个程序需要接受类类型仅在运行时才知道的对象。 I was wondering if it's possible to have the program automatically cast back the objects to the correct class type?
我想知道是否有可能让程序自动将对象转换回正确的类类型?
The following code is what I currently have;以下代码是我目前拥有的; I will explain what I expect it to do step-by-step:
我将逐步解释我期望它做什么:
TryingSomething
instance that adds two sets (one of class type Foo
, one of class type Bar
).TryingSomething
实例,该实例添加两个集合(一个是类类型Foo
,一个是类类型Bar
)。Foo
and Bar
).Foo
和Bar
)。 Will this work? Thanks to anyone who can give me some pointers.感谢任何可以给我一些指示的人。
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{
}
You can use the class objects (runtime types) of the classes for your map keys:您可以将类的类对象(运行时类型)用于映射键:
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{
}
The class TryingSomething
shouldn't be generic because you want to store sets of arbitrary types (chosen dynamically at runtime). TryingSomething
类TryingSomething
应该是泛型的,因为您要存储任意类型的集合(在运行时动态选择)。 Note that this implementation does not check if an inserted set actually contains objects of the specified type at all (neither at insertion nor at retrieval) - the reponsibility here lies with the user of this container class.请注意,此实现根本不检查插入的集合是否实际包含指定类型的对象(无论是在插入时还是在检索时)——这里的责任在于此容器类的用户。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.