Java Generics Capture

时间:2017-04-04 07:43:25

标签: java

我有一些像这样的代码。 Payload是Java对象。

DSRecommendations和LsRecommendations扩展RecEntry

objectMapper和TypeReference来自jackson,RecEntry是我自己的类

有效负载只是recEntry的列表

public enum RecSourceEnum {
    CSELL(DSRecommendations.class),
    LS(LsRecommendations.class);

    private final Class<? extends RecEntry> recEntry;

    <T extends RecEntry> RecSourceEnum(Class<T> recEntry) {
        this.recEntry = recEntry;
    }

    public Class<? extends RecEntry> getRecEntry() {
        return recEntry;
    }
}

    String source = "CSELL";
    Class<? extends RecEntry> clazz = RecSourceEnum.valueOf(source.toUpperCase()).getRecEntry();
                List<RecEntry> recommEntryList = convertFromObj(payload, clazz);

    private static <T extends RecEntry> List<T> convertFromObj(Object payload, Class<T> clazz) throws IOException {
            TypeReference<List<T>> mapType = new TypeReference<List<T>>() {};
            return objectMapper.convertValue(payload, mapType);
        }

当我尝试运行此代码时。我收到了这个错误。

Wrong 2nd argument type. Found: 'java.lang.Class<? extends entry.RecEntry>', required: 'java.lang.Class<T>' less... 

convertFromObj
(Object, java.lang.Class<T>)
in BManagerImpl cannot be applied to
(Object, java.lang.Class<capture<? extends entry.RecEntry>>)
 
 reason: Incompatible equality constraint: RecEntry and capture of ? extends RecEntry

如何解决这个问题?

1 个答案:

答案 0 :(得分:-1)

我不确定这是否真的是你要求的,但我还是决定发布我的答案。

主要类

public static void main(String[] args) throws IOException {
    String source = "CSELL";
    Class<? extends Alphabet> clazz = RecSourceEnum.valueOf(source.toUpperCase()).getRecEntry();

    Alphabet abc = new Alphabet();

    Alphabet val = convertFromObj(abc, clazz);

    System.out.println(clazz);
    System.out.println("A: " + val.getClass());
}   

private static <T extends Alphabet> T convertFromObj(Object payload, Class<T> clazz) throws IOException {
    ObjectMapper om = new ObjectMapper();
    return om.convertValue(payload, clazz);
}

<强> RecSourceEnum

enum RecSourceEnum {
    CSELL(A.class),
    LS(B.class);

    private final Class<? extends Alphabet> recEntry;

    <T extends Alphabet> RecSourceEnum(Class<T> recEntry) {
        this.recEntry = recEntry;
    }

    public Class<? extends Alphabet> getRecEntry() {
        return recEntry;
    }
}

测试类

class Alphabet{
    public String name;
}

class A extends Alphabet{
}

class B extends Alphabet{
}

<强>输出

class test.A
A: class test.A