This line of code
Class<String> cls = (Class<String>) Class.forName("java.lang.String");
Gives compiler warning Type safety: Unchecked cast from Class<capture#1-of ?> to Class<String>
Also, according to API definition it returns returns Class<?>
:
Class<?> Class.forName(String arg)
I do not understand why conversion from Class<?>
to Class<String>
is treated as unchecked (that is compiler cannot check if such cast is possible while compiling).
If it was
Class<String> cls = (Class<String>) Class.forName("some_str_var");
I could understand that compiler cannot know return type of Class.forName() at compile time (because argument is a variable, not a literal) and in runtime type information is erased.
But Class.forName("java.lang.String")
is obviuosly Class<?>
during compilation (and cls
variable in LHS is still Class<String>
), no type information is erased yet (compiler sees source code, not byte-code with erased type-info), and compiler can check everything.
Aucun commentaire:
Enregistrer un commentaire