简体   繁体   English

使用引发异常的方法在静态块中初始化的最终静态变量

[英]Final static variable initialized in static block using method that throws exception

Consider following part of code 考虑下面的代码部分

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
}

I this case I am getting "variable might already have been assigned" on line B, which can be true if I had more lines in try{} block and exception was caused after my variable has been initialized. 在这种情况下,我在行B上获取了“可能已经分配了变量”的信息,如果在try{}块中有更多行,并且在初始化变量后导致异常,则可能为true。 When I remove word final from line A it compiles ok, but I am getting warnings later in static {} block when I am trying to assign imageWidth/height (also final static) using connectionImage.getWidth() (of course if its not null). 当我从A行中删除final单词时,它可以编译,但是稍后当我尝试使用connectionImage.getWidth()分配imageWidth / height(也是final static)时,我在static {}块中收到警告(当然,如果它不为null) )。 The warning is "usage of non-final variable during initialization". 警告是“初始化期间使用非最终变量”。 If I decide to use final in line A and remove line B, I am getting "variable connectionImage might not have been initialized" on line C. 如果我决定在A行中使用final并删除B行,那么我在C行上收到“变量connectionImage可能尚未初始化”的信息。

My question is: Is there a way to have static final variables initialized and usable in static {} block using functions that throws exception (or generally inside try/catch ) or I should handle other way? 我的问题是:是否有一种方法可以使用引发异常的函数(或通常在try/catch内部)将static最终变量初始化并在static {}块中使用,还是应该以其他方式处理? (constructor) (构造函数)

NOTE (if relevant): Yes, the name of this class is to tell you it is inner class. 注意(如果相关):是的,此类的名称是为了告诉您它是内部类。 Also it is static because if it isn't I can't declare static fields inside. 它也是静态的,因为如果不是,我就不能在其中声明静态字段。

I know how to write code which will do what I wan't, but I'd like to have this inner class because of my convenience and to separate some behaviors. 我知道如何编写代码来完成我不希望做的事情,但是由于我的方便,我想拥有这个内部类,并希望将某些行为分开。 I only wan't to know the static final, static block, try/catch situation. 我只是不知道静态的最终静态块,尝试/捕获情况。 I couldn't find good exlpanation for this in google, I even Checked my old 'Thhinking in Java'... 我在Google中找不到很好的解释,我什至检查了我以前的“ Thinkking in Java” ...

Here is something similar Java - Can final variables be initialized in static initialization block? 这是类似Java的东西-最终变量可以在静态初始化块中初始化吗? but author hadn't try to initialize variable in catch, also he is not using them in the static block after assignment so he is not getting "Usege of non-final..." warning later. 但是作者没有尝试在catch中初始化变量,也没有在分配后在静态块中使用它们,因此以后不会收到“ Use of non-final ...”警告。

Basically, you should use a local variable: 基本上,您应该使用局部变量:

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;

Now you know for sure that your connectionImage variable will be assigned exactly once. 现在您可以确定您的connectionImage变量将只分配一次。

I would then use a conditional operator for width , which makes it clearer that there's exactly one assignment: 然后,我将对width使用一个条件运算符,这样可以更清楚地知道只有一个赋值:

width = connectionImage != null ? connectionImage.getWidth() : 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从静态块或方法初始化静态最终int并在注释中使用它 - Initializing a static final int from static block or method and using it in annotations 无法定义私有静态final变量,因为它会抛出异常 - Can't define a private static final variable because it throws an exception 如何使用引发异常的方法初始化最终的静态数据成员 - How To Initialize final static data member with the method which throws Exception 如何在初始化和操作最终静态变量的静态块中禁止串行警告? - How to suppress serial warning for a static block where a final static variable is initialized and manipulated? 静态最终变量以及静态初始化块 - Static final variable along with static initializer block Java - 最终变量可以在静态初始化块中初始化吗? - Java - Can final variables be initialized in static initialization block? 切换语句并在静态块中初始化最终的静态变量 - Switch statement and initializing a final static variable in static block 为什么我不能在非静态块中声明静态最终变量? - Why cant I declare static final variable in non static block? 在初始化静态最终变量时捕获异常 - Catch exception while initializing static final variable 确保在构造函数抛出异常时初始化最终变量 - Making sure that a final variable is initialized when a constructor throws an exception
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM