考虑下面的代码部分
private static class InnerClass
{
private static final BufferedImage connectionImage; // line A
private static final int width;
// other not relevant fields
static
{
try
{
connectionImage = ImageIo.read(...); // doeasn't really matter - any method that throws exception
}
catch(IOException e)
{
// handle
connectionImage = null; // line B
}
if(connectionimage != null) // line C
{
width = connectionImage.getWidth();
}
else
{
width =0;
}
}
// rest of the class definition
}
在这种情况下,我在行B上获取了“可能已经分配了变量”的信息,如果我在try{}
块中有更多行,并且在初始化变量后引起异常,则可能为true 。当我final
从A行删除单词时,它可以编译,但是static {}
当我尝试使用connectionImage.getWidth()
(当然,如果它不为null)分配imageWidth / height(也是最终的静态值)时,在块中稍后收到警告。警告是“初始化期间使用非最终变量”。如果我决定final
在A行中使用并删除B行,则在C行中收到“变量connectionImage可能尚未初始化”的信息。
我的问题是:是否有一种方法可以static {}
使用引发异常(或通常在内部try/catch
)的函数来初始化静态最终变量并在块中使用,还是我应该以其他方式处理?(构造函数)
注意(如果相关):是的,此类的名称是为了告诉您它是内部类。它也是静态的,因为如果不是,我就不能在其中声明静态字段。
我知道如何编写代码来完成我想做的事情,但是由于我的方便,我想拥有这个内部类,并希望将某些行为分开。我只是不知道静态的最终静态块,尝试/捕获情况。我在Google中找不到很好的解释,我什至检查了我以前的“ Thinkking in Java” ...
这是类似Java的东西-最终变量可以在静态初始化块中初始化吗?但是作者没有尝试在catch中初始化变量,也没有在分配后在静态块中使用它们,因此以后不会收到“ Use of non-final ...”警告。
基本上,您应该使用局部变量:
BufferedImage localImage = null;
try
{
localImage = ImageIo.read(...);
}
catch (IOException e)
{
// No need to set a value, given that it's already going to be null.
// You probably want to log though.
}
connectionImage = localImage;
现在您可以确定connectionImage
变量将只分配一次。
然后,我将使用条件运算符作为width
,这样可以更清楚地知道只有一个赋值:
width = connectionImage != null ? connectionImage.getWidth() : 0;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句