jeudi 1 septembre 2016

Dynamically call overloaded method reference based on List Object's type?

Say I have a Java controller class, which I want to have a method that applies a transform to each object in a List/Collection depending on the type of that object. The transforms are of the same name, and are overloaded method references that convert to a common type based on the parameter type. See the example below.

public static List<String> convertList(List<? extends Object> list) {
    return list.stream().map(POJO::convert).collect(Collectors.toList());
}

public static String convert(POJO p) {
    return p.toString();
}

public static String convert(POJO2 p) {
    return p.toString();
}

The above gives an error Incompatible types: cannot infer type-variable(s) R

It works, of course, if I set the method signature to convertList(List<POJO> list), but then it only works for one of the object types. How can I use something like reflection or lazy casting to get one method to work for both convert functions? I cannot edit the class definitions of either POJO or POJO2.





Aucun commentaire:

Enregistrer un commentaire