忽略返回对象时的编译时警告 [英] Compile time warning when ignoring returning object
问题描述
我知道Java通常允许不关心方法中返回的对象,但在这种情况下,我想确保Api的用户将返回的实例添加到列表中,否则将被执行马上.
I know that Java normally allows not caring about the returned object if present from a method, but in this case, I want to make sure that the user of an Api adds the returned instance to a list, otherwise it will be executed straight away.
普通 Java:
Runnable someTask() {
...
}
someTask(); // ok
应该
Runnable someTask() {
...
}
addToExecutionList(someTask()); // ok
someTask(); // gives warning
有没有办法通过编译时警告来防止这种情况发生?
Is there a way to prevent this with say a compile time warning?
推荐答案
有没有办法通过编译时警告来防止这种情况发生?
Is there a way to prevent this with say a compile time warning?
没有.没有办法强制调用者使用方法的返回值.像 FindBugs 之类的东西可能有一个选项可以将其报告为狡猾的代码,如果这对您有帮助的话.
No. There's no way of forcing a caller to use the return value of a method. Something like FindBugs may have an option for reporting it as dodgy code, if that helps you.
这篇关于忽略返回对象时的编译时警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!