简体   繁体   English

空白最终变量

[英]Blank final variables

I'm trying to combine 我试图结合

  1. public access to variable 公众获取变量
  2. non static variable 非静态变量
  3. not predifined value 非预定值
  4. one time set value (final) 一次设定值(最终)
  5. int or Integer 整数或整数

Updated code is not working and the answer on 'how to do it' must be pretty simple, but I need help: 更新后的代码无法正常工作,关于“操作方法”的答案必须非常简单,但我需要帮助:

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;
        }
    }
}

PS I don't want to use (private int + public getter + private setter) 我不想使用的PS(私有int +公共getter +私有setter)

When myObj is null the final fields won't be set. myObj为null时,将不会设置最终字段。 This results in compilation error, they must be set after foo(Object myObj, int extraParam) constructor finishes. 这导致编译错误,必须在foo(Object myObj, int extraParam)构造函数完成后进行设置。

If you need to create an instance of foo could add an else block. 如果需要创建foo的实例,则可以添加else块。

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

or create a factory method to perform the check. 或创建工厂方法以执行检查。

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);
}

When you perform an assignment within a try block, the compiler treats it as “may or may not have happened” after the try … catch … construct, which makes it ineligible for final variables you want to use after that construct. try块中执行赋值时,编译器在try … catch …构造之后将其视为“可能发生或未发生”,这使其不符合要在该构造之后使用的final变量的资格。

The solution is to use temporary non-final variables which you can assign multiple times and perform a definite assignment of the final variables at the end of the operation. 解决方案是使用临时非最终变量,您可以多次分配该临时非最终变量,并在操作结束时对final变量执行明确的分配。

Eg 例如

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;
    }
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM