例如:
javac Foo.java
Note: Foo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
例如:
javac Foo.java
Note: Foo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
当前回答
这个警告也可能会被引发,因为新的HashMap()或新的ArrayList()是泛型类型,必须是特定的,否则编译器将生成警告。
请确保如果您的代码包含以下内容,您必须相应更改
new HashMap() => Map<String,Object> map = new HashMap<String,Object>()
new HashMap() => Map<String,Object> map = new HashMap<>()
new ArrayList() => List<String,Object> map = new ArrayList<String,Object>()
new ArrayList() => List<String,Object> map = new ArrayList<>()
其他回答
我只是想再举一个我经常看到的未检查警告的例子。如果使用实现Serializable等接口的类,通常会调用返回接口对象的方法,而不是实际的类。如果返回的类必须转换为基于泛型的类型,则可以得到此警告。
下面是一个简单(有点傻)的例子:
import java.io.Serializable;
public class SimpleGenericClass<T> implements Serializable {
public Serializable getInstance() {
return this;
}
// @SuppressWarnings("unchecked")
public static void main() {
SimpleGenericClass<String> original = new SimpleGenericClass<String>();
// java: unchecked cast
// required: SimpleGenericClass<java.lang.String>
// found: java.io.Serializable
SimpleGenericClass<String> returned =
(SimpleGenericClass<String>) original.getInstance();
}
}
getInstance()返回一个实现Serializable的对象。必须将此类型转换为实际类型,但这是未检查的类型转换。
我上了两年前的课,也上了一些新课。我在Android Studio中解决了这个问题:
allprojects {
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked"
}
}
}
在我的项目构建中。gradle文件(Borzh解决方案)
如果还剩下一些methods:
@SuppressWarnings("unchecked")
public void myMethod()
{
//...
}
你可以保持它的一般形式,并将其写成:
// list 2 is made generic and can store any type of Object
ArrayList<Object> list2 = new ArrayList<Object>();
将数组列表的类型设置为对象使我们能够存储任何类型的数据。你不需要使用-Xlint或其他任何东西。
此警告意味着您的代码在原始类型上操作,请使用
-Xlint:unchecked
获取详细信息
是这样的:
javac YourFile.java -Xlint:unchecked
Main.java:7: warning: [unchecked] unchecked cast
clone.mylist = (ArrayList<String>)this.mylist.clone();
^
required: ArrayList<String>
found: Object
1 warning
Docs.oracle.com在这里谈到了它: http://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html
例如,当你调用一个返回泛型集合的函数时,你不自己指定泛型参数。
对于一个函数
List<String> getNames()
List names = obj.getNames();
将生成此错误。
要解它,你只需要加上参数
List<String> names = obj.getNames();