来自C++背景,我是RAII模式的忠实粉丝.我已经广泛使用它来处理内存管理和锁管理以及其他用例.
使用Java 1.7,我看到我可以使用try-with-resources模式来创建RAII模式.
我使用RAII创建了一个示例应用程序并且它可以工作,但是我看到java中的编译器警告.
样品申请
try(MyResource myVar = new MyResource(..))
{
//I am not using myVar here
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
warning: [try] auto-closeable resource node is never referenced in body of corresponding try statement
Run Code Online (Sandbox Code Playgroud)
我理解警告,这意味着我应该在try块中使用变量,我不需要一直这样做.
看看这个我假设Java并没有真正支持RAII,我可能误用了仅用于资源管理的功能,而不是C++中的RAII等价物.
几个问题:
for 4我正在考虑将构造函数调用拆分为更简单的构造函数和像这样的实例方法
try(MyResource myVar = new Resource())
{
myvar.Initialize()
....
}
Run Code Online (Sandbox Code Playgroud)
这解决了编译器的问题,但从设计的RAII中获取了本质.
我从我的蚂蚁脚本中调用javac,如下所示:
<javac srcdir="src"
destdir="build/classes" source="1.6"
target="1.6" debug="true" encoding="Cp1252"
nowarn="true">
Run Code Online (Sandbox Code Playgroud)
但它仍然会在输出中抛出编译器警告:
[javac] Compiling 73 source files to C:\IKOfficeRoot\Java\ERP\Framework\build\classes
[javac] C:\IKOfficeRoot\Java\ERP\Framework\src\de\ikoffice\util\LoggerFactory.java:49: warning: sun.reflect.Reflection is Sun proprietary API and may be removed in a future release
[javac] return Logger.getLogger(Reflection.getCallerClass(2));
[javac] ^
[javac] Note: C:\IKOfficeRoot\Java\ERP\Framework\src\de\ikoffice\db\SingleShotResultSet.java uses or overrides a deprecated API.
[javac] Note: Recompile with -Xlint:deprecation for details.
[javac] Note: Some input files use unchecked or unsafe operations.
[javac] Note: Recompile with -Xlint:unchecked for details.
[javac] 1 warning
Run Code Online (Sandbox Code Playgroud)
我也试过了
<compilerarg line="-Xlint:-unchecked -Xlint:-deprecation"/>
Run Code Online (Sandbox Code Playgroud)
和
<compilerarg …Run Code Online (Sandbox Code Playgroud)