Creating a generic method that returns value of different type based on the type argument it is passed. Here is the code:
public class Main {
public static void main(String[] args) {
Class<String> stringClass = String.class;
List<Map<String, String>> listMapValue = getValue(new TypeReference<>() {});
System.out.println("Returned value for List<Map<String, String>>: " + listMapValue);
List<Integer> value = getValue(new TypeReference<List<Integer>>() {});
for (Integer i : value) {
System.out.println(value);
}
System.out.println(value);
}
@SuppressWarnings("unchecked")
public static <T> T getValue(TypeReference<T> typeReference){
Type type = typeReference.getType();
if(type.getTypeName().equals("java.util.List<java.util.Map<java.lang.String, java.lang.String>>")){
return (T) List.of(Map.of("k1", "v1"));
}
if(type.getTypeName().equals("java.util.List<java.lang.Integer>")){
// how to detect compile time error here
return (T) List.of(Map.of("k1", "v1")); // wrong type being returned
// return (T) List.of(1, 2); // ideal return value
}
System.out.println(type.getTypeName());
return null;
}
}
Issue is that the based on the type of argument passed to getValue()
it can return completely different type of value and this won’t be detected at the compile time.