class SomeClass<E> {
Map<String, String> someMethod();
}
和用法
SomeClass a = new SomeClass();
a.someMethod().get("foo") // returns object, not string!
//This code would not even compile
String s = a.someMethod().get("foo");
但如果我从 SomeClass 中删除泛化 (
如果我将此方法提取到接口(interface)并在声明中使用接口(interface),它也有效:
interface Foo {
Map<String, String> someMethod();
}
class SomeClass implements Foo {
//.....
}
Foo foo = new SomeClass();
String s = foo.someMethod().getString("A");//it works
为什么会这样?我在哪里可以读到它?最好的解决方法是什么? 谢谢。
最佳答案
解决方案不是让 SomeClass
成为非泛型——而是避免使用原始类型。例如,这很好用:
import java.util.*;
class SomeClass<E> {
Map<String, String> someMethod() {
return null;
}
}
public class Test {
public static void main(String[] args) {
SomeClass<Integer> a = new SomeClass<Integer>();
String value = a.someMethod().get("foo");
}
}
诚然,如果您使用原始类型,该方法有效地应用了类型删除,这有点奇怪 - 但您应该从根本上避免这样做。
我目前找不到任何关于 JLS 中原始类型行为的解释,但是 section 4.8确实包含此警告:
The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.
关于Java:在不同于泛型类参数的方法返回中使用泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3132381/