如何在Java中找到已实现接口的所有子类?

时间:2019-03-31 22:14:23

标签: java reflection

如果接口用作DynamoDBTypeConverter的类型参数(例如DynamoDBTypeConverter),则如何使用已实现的接口获取Subclass对象。

public enum state implements EnumInterface{
    CREATED("0");
}

public enum color implements EnumInterface{
    GREEN("0");
}

public interface EnumInterface{
    void getStatus();
}

public class DynamoDbEnumConverter implements DynamoDBTypeConvereter<String,EnumInterface>{
    public EnumInterface unconvert(String value){
        // find Object run time, EnumInterface represent color or stat
    }
}

获取Enum接口是使用unconvert方法表示颜色还是状态。

1 个答案:

答案 0 :(得分:0)

签出此页面:What are Reified Generics? How do they solve Type Erasure problems and why can't they be added without major changes?

泛型在Java中是被擦除

要使代码正常工作而又不至于乱码,唯一的方法是为每个DynamoDbEnumConverter提供一个EnumInterface实例:

class DynamoDbEnumConverter<T extends Enum<T> & EnumInterface> implements DynamoDBTypeConvereter<String, T> {
    private Class<T> enumType;

    public DynamoDbEnumConverter(Class<T> enumType) {
        this.enumType = enumType;
    }

    public EnumInterface unconvert(String value) {
        return Enum.valueOf(enumType, value);
    }
}

然后:

DynamoDbEnumConverter<Color> colorConverter = new DynamoDbEnumConverter<>(Color.class);