2017-04-04 66 views
0

我有這樣的代碼。 Payload是Java對象。Java泛型捕獲

DSRecommendations和LsRecommendations延伸RecEntry

objectMapper和TypeReference從傑克遜和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 

如何解決這個問題?

+0

你有一個列表'',你想一個'列表'分配給它。在X和Y之間存在繼承的事實並不意味着在「列表」和「列表」之間存在繼承關係。 – RealSkeptic

回答

-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