例如:

javac Foo.java
Note: Foo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

当前回答

我上了两年前的课,也上了一些新课。我在Android Studio中解决了这个问题:

allprojects {

    gradle.projectsEvaluated {
        tasks.withType(JavaCompile) {
            options.compilerArgs << "-Xlint:unchecked"
        }
    }

}

在我的项目构建中。gradle文件(Borzh解决方案)

如果还剩下一些methods:

@SuppressWarnings("unchecked")
public void myMethod()
{
    //...
}

其他回答

我上了两年前的课,也上了一些新课。我在Android Studio中解决了这个问题:

allprojects {

    gradle.projectsEvaluated {
        tasks.withType(JavaCompile) {
            options.compilerArgs << "-Xlint:unchecked"
        }
    }

}

在我的项目构建中。gradle文件(Borzh解决方案)

如果还剩下一些methods:

@SuppressWarnings("unchecked")
public void myMethod()
{
    //...
}

解决方案是在<>中使用特定的类型,如ArrayList<File>。

例子:

File curfolder = new File( "C:\\Users\\username\\Desktop");
File[] file = curfolder.listFiles();
ArrayList filename = Arrays.asList(file);

以上代码生成警告,因为ArrayList不是特定类型。

File curfolder = new File( "C:\\Users\\username\\Desktop");
File[] file = curfolder.listFiles();
ArrayList<File> filename = Arrays.asList(file);

上面的代码就可以了。唯一的变化是在ArrayList之后的第三行。

此警告意味着您的代码在原始类型上操作,请使用

-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

我只是想再举一个我经常看到的未检查警告的例子。如果使用实现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文件来了解这个错误是在哪里产生的。