Specify the type of class object

The following code calls the setProperty method on Camel Exchange

List<Message> list = oldExchange.getProperty("p",List.class);

The goal is that I retrieve the object Listthat I previously saved with the instance Exchange.

As soon as this code stands, I get a compiler warning (Security Type: an expression of type List needs an raw conversion to match List).

I know that I can get away from this by adding an annotation @SuppressWarnings("unchecked"), but is there any way that I can fix it by modifying the ad List.class?

The method getPropertyhas the following signature <T> T getProperty(String name, Class<T> type)

+4
source share
2 answers

, , , , , List, , Message. , ClassCastException , - Message m = list.get(0);

, , :

public static <T> List<T> checkElements(List<?> list, Class<T> elementClass) {
    for(Object e : list) {
        elementClass.cast(e); // throw CCE on wrong element
    }
    @SuppressWarnings("unchecked")
    List<T> result = (List<T>)list;
    return result;
}

- @SuppressWarnings, "library", . - :

List<Message> list = checkElements(oldExchange.getProperty("p",List.class), Message.class);

, . 100% , , @SuppressWarnings .

+1

, - .

, :

@SuppressWarnings("unchecked")
static <T> T  myGetProperty(String name, Class<?> type) {
    return (T) getProperty(name, type);
}

:

List<String> listOfStrings = myGetProperty("a", List.class);

, , , .

+2

Source: https://habr.com/ru/post/1605898/


All Articles