java expression 强制出现,为什么java编译器不报告Intellij中多播表达式的未经检查的强制转换警告?...

本文讨论了在IntelliJ IDEA中使用JDK1.8.0_121时,为何代码没有报告未检查警告的情况。作者提供了一个示例代码,展示了即使存在潜在的类型安全问题,IDEA也不会显示警告。解决方法是在IDE的Java编译器设置中添加`-Xlint:unchecked`选项。当在命令行使用`javac`编译时,也会提示如何启用未检查警告。文章探讨了IDEA与命令行编译器在处理未检查警告方面的行为一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

& Serializable> T createdBy(AtomicInteger counter) {

// v--- if I removed the first cast expression, I can't compile it

return (T) (Supplier & Serializable) counter::incrementAndGet;

// ^--- it should be reports unchecked warnings, but it doesn't

}

And the following code has reported unchecked cast warnings:

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 serialized = serialized(createdBy(counter));

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

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

T serialized(T value) {

return deserialize(serialize(value));

}

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

解决方案

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:

RDFVH.png

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.

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

Atdpb.png

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.io.Serializable

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值