[英]Ensure type safety with Java generics
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? 如何确保不使用原始类型B
调用此方法,并且编译器始终检查指定的String类型?
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. 原因是为了与Java的预通用版本向后兼容。
If the compiler warnings are turned on ( -Xlint:unchecked
), you will get a warning if that method is called with a raw type: 如果打开编译器警告( -Xlint:unchecked
),如果使用原始类型调用该方法,则会收到警告:
warning: [unchecked] unchecked conversion A a = method(new B()); 警告:[未选中]未选中的转换A a =方法(新B());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.