空白最终变量

时间:2018-11-09 17:02:14

标签: java int final

我正在尝试合并

  1. 公开访问变量
  2. 非静态变量
  3. 非预定值
  4. 一次设定值(最终)
  5. int或Integer

更新后的代码不起作用,关于“操作方法”的答案必须非常简单,但我需要帮助:

public class foo
{
    public final int smth; //Variable might not have been initialized
    public final Integer smthElse; //Variable might not have been initialized

    public foo(JSONObject myObj)
    {
        if(myObj != null) {
            try {
                int extraParam = Integer.parseInt("ABCD"); //This is just an example for Exception to be called
                smth = extraParam;
                smthElse = extraParam;
            } catch (Exception e) {}
        } else {
            smth = 1;
            smthElse = 2;
        }
    }
}

P.S。我不想使用(私有int +公共getter +私有setter)

2 个答案:

答案 0 :(得分:3)

myObj为null时,将不会设置最终字段。这会导致编译错误,必须在foo(Object myObj, int extraParam)构造函数完成后进行设置。

如果您需要创建foo的实例,可以添加一个else块。

public foo(Object myObj, int extraParam) {
  if (myObj != null) {
    smth = extraParam;
    smthElse = extraParam;
  } else {
    smth = 0;
    smthElse = 0;
  }
}

或创建一种工厂方法来执行检查。

private foo(int extraParam) {
  smth = extraParam;
  smthElse = extraParam;
}

public static foo from(Object myObj, int extraParam) {
  return (myObj == null) ? new foo(0) : new foo(extraParam);
}

答案 1 :(得分:1)

当您在try块中执行赋值时,编译器将其视为try … catch …构造之后的“可能发生或未发生”,这使其不符合final变量您想在该构造之后使用。

解决方案是使用临时的非最终变量,您可以对其进行多次分配,并在操作结束时对final变量进行明确分配。

例如

public class Foo
{
    public final int smth;
    public final Integer smthElse;

    public Foo(JSONObject myObj) {
        int smthValue = 1;
        Integer smthElseValue = 2;

        if(myObj != null) try {
            int extraParam = Integer.parseInt("ABCD"); //This is just an example
            smthValue = extraParam;
            smthElseValue = extraParam;
        } catch (Exception e) {}

        smth = smthValue;
        smthElse = smthElseValue;
    }
}
相关问题