简体   繁体   中英

How to find all sub classes of implemented interface in java?

How to get Subclass object using implemented interface, if interface is used as Type Parameter for DynamoDBTypeConverter.(eg DynamoDBTypeConverter ).

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

Get whether Enum interface represents color or state in unconvert method.

Check this page out: What are Reified Generics? How do they solve Type Erasure problems and why can't they be added without major changes?

Generics are erased in Java.

The only way you're going to get your code to work without hacking around is by providing one instance of the DynamoDbEnumConverter for each 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);
    }
}

And then:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM