Instantiate Parameterized Type class with Class<?> variable

869 Views Asked by At

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.

1

There are 1 best solutions below

9
On

Given the constructor in the Bar class, in order to instantiate a new Bar<V> object, you need an object of type V.

So, your problem translates into instantiating an object of type Class<V>. More specifically, assuming an existing Foo object and a getType() method in the Foo class, you would do something like:

Foo foo = ... // Existing Foo object
Class<V> type = foo.getType();
V value = instantiate(type); // TODO: Implement instatiate()
Bar<V> bar = new Bar(value);

The trick then is the implementation of the instantiate() method. If Class<V> has a no-args constructor, then you can just call

V value = type.newInstance();

Not all classes have a default constructor, though, so there is no generic solution for all cases.