Meyer Cohen
Meyer Cohen

Reputation: 360

Java Generic return dynamic type

Imagine a situation where you have this:

// Marker
interface Type {}

interface CustomType extends Type {
    int getSomething();
    int getAnotherThing();
}

class CustomTypeImpl implements CustomType {
    public int getSomething() {
        return 1;
    }
    public int getAnotherThing() {
        return 2;
    }
}

In another class, I want to have a generic method like this :

public <T extends CustomType> T getFromInterface(Class<T> clazz)

that return an implementation of the class I put in parameter. For example, I want to call this method like below : SomeInstanceOfClass.getFromInterface(CustomType.class) and it returns an instance of CustomTypeImpl.

@EDIT : I forgot to mention that I have access to a method that stores all interfaces that can be used as argument of getFromInterface(Class<T> clazz) method.

The signature of this method is : public Set<? extends Class<? extends Type>> allTypes()

How can I manage to do this please ?

Upvotes: 0

Views: 1672

Answers (1)

Mykhailo Hodovaniuk
Mykhailo Hodovaniuk

Reputation: 521

You can use reflection and create a new instance with the class object. The information about what class implements some interface can be stored in some map.

private static final Map<Class<?>, Class<?>> interfaceToImplementationMap = new HashMap<Class<?>, Class<?>>() {{
    put(CustomType.class, CustomTypeImpl.class);
}};

public static void main(String[] args) throws InstantiationException, IllegalAccessException {
    CustomType instance = getFromInterface(CustomType.class);
    System.out.println(instance);
}

public static <T> T getFromInterface(Class<T> clazz) throws IllegalAccessException, InstantiationException {
    return clazz.cast(interfaceToImplementationMap.get(clazz).newInstance());
}

Upvotes: 2

Related Questions