I have some generic code which I cannot figure out how to legitimately prevent getting warnings from; I am using @SuppressWarnings(“unchecked”) for the moment, since it seems that casting a generic type can’t be done without warnings.
How can I get rid of the annotation?
What I have is:
public MyObject(SharedContext<Object> ctx) {
super(ctx); // set protected field 'context'
...
context.set("Input Fields" ,Collections.synchronizedMap(new TreeMap<String,Pair<String,Boolean>>(String.CASE_INSENSITIVE_ORDER)));
context.set("Output Fields" ,Collections.synchronizedMap(new TreeMap<String,String> (String.CASE_INSENSITIVE_ORDER)));
context.set("Event Registry",new EventRegistry(log) );
}
@SuppressWarnings("unchecked")
protected void startup() {
inputFields =(Map<String,Pair<String,Boolean>>)context.get("Input Fields" ,null);
outputFields =(Map<String,String> )context.get("Output Fields" ,null);
eventRegistry =(EventRegistry )context.get("Event Registry",null);
...
}
The protected variable context is type SharedContext<Object>.
Without the annotation the compiler gives warnings:
...\MyClass.java:94: warning: [unchecked] unchecked cast
found : java.lang.Object
required: java.util.Map<java.lang.String,com.mycompany.Pair<java.lang.String,java.lang.Boolean>>
inputFields =(Map<String,Pair<String,Boolean>>)context.get("Input Fields" ,null);
^
...\MyClass.java:95: warning: [unchecked] unchecked cast
found : java.lang.Object
required: java.util.Map<java.lang.String,java.lang.String>
outputFields =(Map<String,String> )context.get("Output Fields" ,null);
After some further research I believe I have found a reasonable alternative, which at least limits the suppression annotation to just one global static utility method to do an unchecked cast.
The self contained test program which follows should be clear enough:
Another blog suggested an improvement to this utility method:
forcing what is returned to be a subclass of the parameter passed in.
Assuming I put uncheckedCast into public utility class GenUtil, my startup method in the question would have no (useless) warnings emitted and look like: