为什么java编译器不报告Intellij中多播表达式的未经检查的强制转换警告? [英] why java compiler doesn't report unchecked cast warnings for multi-cast expression in Intellij?

查看:875
本文介绍了为什么java编译器不报告Intellij中多播表达式的未经检查的强制转换警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码没有报告Intellij IDEA与 jdk 1.8.0_121 的未经检查的警告,因为供应商< R> &安培; Serializable T 的超类型?

Why the code below didn't report unchecked warnings by Intellij IDEA with jdk 1.8.0_121 since Supplier<R> & Serializable is the supertype of T?

<T extends Supplier<Integer> & Serializable> T createdBy(AtomicInteger counter) {
    //      v--- if I removed the first cast expression, I can't compile it
    return (T) (Supplier<Integer> & Serializable) counter::incrementAndGet;
    //           ^--- it should be reports unchecked warnings, but it doesn't

}

以下代码报告未经检查的投射警告:

And the following code has reported unchecked cast warnings:

<T, R extends T> R apply(T value) {
    return (R) value;
    //      ^--- unchecked cast 
}

为什么会出现此问题,感兴趣的事情发生在我编写下面的代码用于链接具有多超类型的类型:

Why this question occurs, the interested thing occurs during I write the code at below for chaining a type with multi-supertypes:

AtomicInteger counter  = new AtomicInteger(0);
Supplier<Integer>  serialized = serialized(createdBy(counter));

assert serialized.get() == 1; // ok
assert counter.get() == 0 ; // ok

<T extends Serializable> T serialized(T value) {
    return deserialize(serialize(value));
}

我搜索过JLS,但我找不到确切的信息有利证据。有人可以告诉我原因吗?

I have searched through the JLS, but I can't find out the exactly favorable evidence. Could someone tell me why?

推荐答案

在IntelliJ IDEA中,java编译器报告未经检查的警告,你需要添加 -Xlint:未经检查的 Java编译器选项|其他命令行参数:

In IntelliJ IDEA for the java compiler to report unchecked warnings you need to add -Xlint:unchecked option to the Java Compiler | Additional Command line parameters:

如果您尝试使用它编译它命令行 javac ,它也不会报告警告本身,但会告诉你如何启用未经检查的警告:

If you try to compile it using the command line javac, it will also not report you the warning itself, but will tell how to enable unchecked warnings:

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

如果未指定此选项,IntelliJ IDEA将显示相同的消息:

The same message is displayed by IntelliJ IDEA if this option is not specified:

添加 -Xlint后:取消选中选项,输出将更改为:

After you add -Xlint:unchecked option, the output would change to:

Information:javac 1.8.0_121 was used to compile java sources
Information:01.07.2017 16:07 - Compilation completed successfully with 1 warning in 2s 553ms
D:\work\attaches\unchecked\src\Main.java
    Warning:Warning:line (9)java: unchecked cast
  required: T
  found:    java.lang.Object&java.util.function.Supplier<java.lang.Integer>&java.io.Serializable

如您所见,IntelliJ IDEA的行为与命令行 javac完全相同

As you can see, IntelliJ IDEA behaves exactly the same as the command line javac.

这篇关于为什么java编译器不报告Intellij中多播表达式的未经检查的强制转换警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆