Java Generic返回动态类型

时间:2017-01-23 15:12:28

标签: java generics

想象一下你有这样的情况:

// 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;
    }
}

在另一个课程中,我希望有一个像这样的通用方法:

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

返回我放入参数的类的实现。例如,我想调用此方法,如下所示:SomeInstanceOfClass.getFromInterface(CustomType.class)并返回CustomTypeImpl的实例。

@EDIT :我忘了提到我有权访问一个存储所有可用作getFromInterface(Class<T> clazz)方法参数的接口的方法。

此方法的签名为:public Set<? extends Class<? extends Type>> allTypes()

我怎么能设法做到这一点?

1 个答案:

答案 0 :(得分:2)

您可以使用反射并使用类对象创建新实例。有关哪个类实现某些接口的信息可以存储在某个映射中。

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());
}
相关问题