Ensure type safety with Java generics
-
21-06-2021 - |
Question
I am trying to improve the type safety of the following method:
A<String> method(B<String> arg);
How do I make sure that this method is not called with a raw type B
and that compiler always checks for String type specified?
Solution
You can't prevent someone from calling a method with a raw type.
The reason is for backward compatibility with pre-generic versions of java.
OTHER TIPS
If the compiler warnings are turned on (-Xlint:unchecked
), you will get a warning if that method is called with a raw type:
warning: [unchecked] unchecked conversion A a = method(new B());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow