在这个简化的例子中,我有一个泛型类,以及一个返回Map而不管类型参数的方法.当我没有在包含类上指定类型时,为什么编译器会清除地图上的类型?
import java.util.Map;
public class MyClass<T>
{
public Map<String, String> getMap()
{
return null;
}
public void test()
{
MyClass<Object> success = new MyClass<Object>();
String s = success.getMap().get("");
MyClass unchecked = new MyClass();
Map<String, String> map = unchecked.getMap(); // Unchecked warning, why?
String s2 = map.get("");
MyClass fail = new MyClass();
String s3 = fail.getMap().get(""); // Compiler error, why?
}
}
Run Code Online (Sandbox Code Playgroud)
我得到这个编译错误.
MyClass.java:20: incompatible types
found : java.lang.Object
required: java.lang.String
String s3 = fail.getMap().get(""); // Compiler error
Run Code Online (Sandbox Code Playgroud) 当我编译下面的类(这里可用,添加main方法以在单个类中重现问题)时,我在IntelliJ或maven命令行中收到以下编译器警告:
java: /Users/luigi/var/src/owner/src/test/java/org/aeonbits/owner/multithread/ThreadBase.java uses unchecked or unsafe operations.
java: Recompile with -Xlint:unchecked for details.
Run Code Online (Sandbox Code Playgroud)
然后我添加了-Xlint:unchecked to maven以查看详细信息,我得到了:
[WARNING] /Users/luigi/var/src/owner/src/test/java/org/aeonbits/owner/multithread/ThreadBase.java:[74,45] unchecked conversion
required: java.util.List<java.lang.Throwable>
found: java.util.List
Run Code Online (Sandbox Code Playgroud)
类源代码如下(已添加main以在单个类中重现问题):
package org.aeonbits.owner.multithread;
import org.aeonbits.owner.Config;
import org.aeonbits.owner.UtilTest.MyCloneable;
import java.util.ArrayList;
import java.util.List;
import static org.aeonbits.owner.UtilTest.debug;
abstract class ThreadBase<T extends Config> extends Thread implements MyCloneable {
private static long counter = 0;
final long uniqueThreadId = ++counter;
final T cfg;
final Object lock;
final int loops;
final List<Throwable> errors = new ArrayList<Throwable>();
ThreadBase(T cfg, Object …Run Code Online (Sandbox Code Playgroud) 今天我遇到了javac关于泛型类型推理的奇怪行为.这是用于说明这种奇怪行为的示例类:
import java.util.Map;
import java.util.Collections;
import java.util.HashMap;
public class Test {
protected <T> T strange(T t, Map<String, String> map) {
return t;
}
protected void ok(Map<String, String> map) {}
protected <T> T test(T t) {
T res = strange(t , new HashMap<String, String>());
//Doesn't work
//res = strange(t, new <String, String>HashMap());
ok(new <String, String>HashMap());
res = strange(t, Collections.<String, String>emptyMap());
//Doesn't work
//res = strange(t, Collections.EMPTY_MAP);
res = strange(t, (Map<String, String>) Collections.EMPTY_MAP);
ok(Collections.EMPTY_MAP);
return res;
}
}
Run Code Online (Sandbox Code Playgroud)
注意//Doesn't …