मैं एक parametrized मूल्य है, जो रनटाइम के दौरान हल हो गई है:जेनेरिक चर को रनटाइम पर हल होने पर अनचेक कास्ट से कैसे बचें?
public class GenericsMain {
public static void main(String... args) {
final String tag = "INT";
Field field = resolve(tag);
if (tag.equals("INT")) {
/*
In here I am using the "secret knowledge" that if tag equals INT, then
field could be casted to Field<Integer>. But at the same time I see an unchecked cast
warning at here.
Is there a way to refactor the code to be warning-free?
*/
Field<Integer> integerField = (Field<Integer>) field;
foo(integerField);
}
}
public static Field resolve(String tag) {
switch (tag) {
case "INT":
return new Field<>(1);
case "DOUBLE":
return new Field<>(1.0d);
default:
return null;
}
}
public static <T> void foo(Field<T> param) {
System.out.println(param.value);
}
static class Field<T> {
public final T value;
public Field(T value) {
this.value = value;
}
}
}
वहाँ एक रास्ता कोड ऊपर (एक लंबे टिप्पणी के साथ चिह्नित) में अनियंत्रित डाली से बचने के लिए है?
सीधे नहीं। (जावा प्रवाह प्रकारों का समर्थन नहीं करता है।) हालांकि आप यहां विज़िटर पैटर्न का उपयोग कर सकते हैं। – aioobe
इस प्रश्न पर एक नज़र डालें: http://stackoverflow.com/questions/1129795/what-is-suppresswarnings-unchecked-in-java – stevecross
@aioobe मैं वास्तव में अच्छा होगा यदि आप एक उदाहरण के साथ विस्तृत करते हैं। –