(Note: I have searched multiple questions on SO in this similar domain, but I never encountered an answer specific to my idea).
Consider if I have a class or enum Foo
where each instance has a Class<?> type
field:
public enum Foo {
A (Integer.class), B (Double.class), C (String.class);
public final Class<?> type;
Foo(Class<?> type) {
this.type = type;
}
}
Then I have a generic class Bar<V>
:
public class Bar<V> {
private V value;
// default constructor
public Bar() {}
// getter
public V getValue(){
return value;
}
// setter
public void setValue(V value){
this.value = value;
}
}
Is it possible to instantiate an instance of Bar
with the type from the Class<?> type
field of a given Foo
without knowing the specific type of Foo.type
? For instance, I would call this in either a static method, or some kind of factory method.
Edit:
To specify the function of Bar: Bar wraps around a value with a simple getter/setter, and has a consistent interface, but an unknown type. The benefit of my idea would be to create instances of Bar based off of an instance of Foo. For instance, use value of Foo.A.type
(which is Integer.class
) to instantiate a Bar<Integer>
without knowing ahead of time that Foo.A.type
has a value of Integer.class
.