Reputation: 1830
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
).Foo
and Bar
). Will this work? If not, is there an alternative that allows me to retrieve the objects back in their correct class type? 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{
}
Upvotes: 2
Views: 140
Reputation: 2789
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). 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.
Upvotes: 1