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
.
Given the constructor in the
Bar
class, in order to instantiate a newBar<V>
object, you need an object of typeV
.So, your problem translates into instantiating an object of type
Class<V>
. More specifically, assuming an existingFoo
object and agetType()
method in theFoo
class, you would do something like:The trick then is the implementation of the
instantiate()
method. IfClass<V>
has a no-args constructor, then you can just callNot all classes have a default constructor, though, so there is no generic solution for all cases.