import java.util.Map;
import java.util.Optional;
import java.util.HashMap;
class Main {
public static void main(String[] args) {
final Map<String, Object> ctx = getAMap();
System.out.println(ctx);
// This line succeeds, even though the fully-qualified syntax specifies Integer when attempting to get a String value
System.out.println(Main.<Integer>getValue(ctx, "STR"));
System.out.println();
Main.<Integer>getValue(ctx, "STR");
// The same code fails when we try to assign "ING" to `Integer a`, not during the cast in `getValue`
// Integer a = Main.<Integer>getValue(ctx, "STR");
// System.out.println(a);
System.out.println();
Main.<String>getValue(ctx, "INT");
// This line fails to cast String to Integer during printing, again not during the cast in `getValue`
// System.out.println(Main.<String>getValue(ctx, "INT"));
System.out.println();
// This line prints "true"
System.out.println(Main.<Foo>getValue(ctx, "BOOL"));
// but this one fails at compile time, because "Main.Foo cannot be converted to Boolean"
// System.out.println(Main.<Foo>getValue(ctx, "BOOL") instanceof Boolean);
System.out.println();
// This case works consistently
System.out.println(Main.<String>getValue(ctx, "ABSENT"));
}
public static <T> T getValue(Map<String, Object> context, String key) {
if (context.containsKey(key)) {
Object obj = context.get(key);
System.out.println(obj.getClass().getName());
T cast = (T) obj;
System.out.println("Cast to " + cast.getClass().getName());
return cast;
} else {
return null;
}
}
public static Map<String, Object> getAMap() {
Map<String, Object> aMap = new HashMap<String, Object>();
aMap.put("STR", "ING");
aMap.put("INT", 1);
aMap.put("BOOL", true);
return new HashMap<>(aMap);
}
private class Foo {
public String toString() {
return "FooFooFoo";
}
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: