简体   繁体   English

确保字段是从构造函数初始化的

[英]Making sure fields are initialized out of constructor

Edit: Sorry for my previous question, the final keyword will confusing you, It's not appropriate. 编辑:对不起我之前的问题, 最后的关键字会让你感到困惑,这是不合适的。 And sorry for my poor English too. 抱歉我的英语也很糟糕。

-----Question------ - - -题 - - -

Assume I have a model class without any constructor, because I need to initialize it within many different logic. 假设我有一个没有任何构造函数的模型类,因为我需要在许多不同的逻辑中初始化它。 But i have a notnull keyword. 我有一个notnull关键字。

public class Model {
    public notnull String name;
    public notnull String address;
    public notnull int age;
}

And I need to use it in different place but keep checking if all notnull fields were initialized in compile time 我需要在不同的地方使用它,但继续检查所有notnull字段是否在编译时初始化

Model m = new Model();
m.name = "Hello";
m.age = 15;
// syntax error, you should set Model.address

Or 要么

Model m1 = new Model();
m1.address = "World";
m1.age = 20;
// syntax error, you should set Model.name

How can I achieve that in java? 我怎样才能在java中实现这一点? Thx. 谢谢。

assume I have a model class without any constractor 假设我有一个没有任何约束器的模型类

This is not possible. 这是不可能的。 Every class has a constructor. 每个类都有一个构造函数。 If you do not define one you end up with the default constructor. 如果您没有定义一个,则最终使用默认构造函数。 In your case: 在你的情况下:

public Model() {
    super();
}

checking if all final field were initialized 检查是否所有最终字段都已初始化

First, final fields must be initialized, otherwise the compiler will not compile. 首先,必须初始化final字段,否则编译器将无法编译。 Hence you have to have to initialize final fields either: 因此,您必须初始化最终字段:

  • in the constructor 在构造函数中
  • when declaring the final field 在宣布最终字段时

Constructor Initialization 构造函数初始化

public final String name;
public final int age;

public Model() {
    this.name = "Hello";
    this.age = 13;
}

Declaration Initialization 声明初始化

public final String name = "Hello";
public final int age = 13;

public Model() {
    super();
}

You can achieve what you seems to want with something like this: 你可以实现你似乎想用这样的内容:

public class Model {
    private final String name;
    private final String address;
    private final int age;

    public Model(final String name, final String address, final int age) {
        if (name == null) {
            throw new IllegalArgumentException("please provide a name");
        }
        if (address == null) {
            throw new IllegalArgumentException("please provide an address");
        }
        this.name = name;
        this.address = address;
        this.age = age;
    }

    // getters
}

Usage: 用法:

new Model("World", "Some address", 20) // OK
new Model("World", null, 20) // Exception because null address.

You should look at the Builder Pattern. 你应该看看Builder模式。 There are number of articles that you can find on the internet on how to use it. 您可以在互联网上找到有关如何使用它的文章。 This is one example https://jlordiales.me/2012/12/13/the-builder-pattern-in-practice/ . 这是一个例子https://jlordiales.me/2012/12/13/the-builder-pattern-in-practice/ Using the Builder pattern you can validate if certain fields are set or not and throw exception if there are not. 使用Builder模式,您可以验证是否设置了某些字段,如果没有,则抛出异常。

If only final : You can either instantiate them where you declare or instantiate inside the constructor. 如果只是final:您可以在构造函数内声明或实例化的位置实例化它们。

If final + static: You MUST instantiate them where you declared. 如果是final + static:你必须在你声明的地方实例化它们。

So since they are not static you need to instantiate where you specified them or in the constructor. 因此,由于它们不是静态的,因此需要实例化指定它们的位置或构造函数。

Assume I have a model class without any constructor because I need to initialize it within many different logic. 假设我有一个没有任何构造函数的模型类,因为我需要在许多不同的逻辑中初始化它。 But I have a notnull keyword. 但我有一个notnull关键字。

You need to note that even if you don't write any constructor, the compiler will provide a default no-argument constructor which will initialize all fields in the object to the default values automatically (ie, String types to null and int types to zero values, etc..) 您需要注意的是, 即使您没有编写任何构造函数,编译器也会提供一个默认的无参数构造函数 ,它会自动将对象中的所有字段初始化为默认值(即String类型为nullint类型为零)价值观等。)


The class constructor is a right place to validate all mandatory fields are provided or not , so create your own constructor to check all mandatory fields are passed in during the object creation: 类构造函数是验证所有必需字段是否提供的正确位置 ,因此创建自己的构造函数以检查在对象创建期间传递的所有必填字段

public class Model {
    private String name;
    private String address;
    private int age;

    public Model(String name, String address, int age) {
         if(name == null) { 
               throw new IllegalArgumentException(" Name is mandatory ");
         } 
         if(address == null) { 
               throw new IllegalArgumentException(" Address is mandatory ");
         }
         if(age < 0) { 
               throw new IllegalArgumentException(" Age is Invalid ");
         }
         this.name = name;
         this.address = address;
         this.age = age;
    }
   //Add getters and setters
}

Also, encapsulate the data of your Model class by marking your fields private (shown above). 此外,通过将字段标记为private 封装 Model的数据 (如上所示)。

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

相关问题 确保在构造函数抛出异常时初始化最终变量 - Making sure that a final variable is initialized when a constructor throws an exception 确保使用Java初始化final字段 - Making sure a final field is initialized in Java 是否在 Java 中运行构造函数代码之前初始化字段? - Are fields initialized before constructor code is run in Java? 为什么字段似乎在构造函数之前被初始化? - Why do fields seem to be initialized before constructor? Javassist报告字段在构造函数中初始化后为空 - Javassist reports fields are null after being initialized in constructor 使用 super() 构造函数时,未初始化空白最终字段 - Blank final fields are not initialized when using a super()-constructor 如何让参数化构造函数链中的派生类访问使用派生构造函数初始化的基类的字段 - How to let a derived class in a parameterized constructor chain access fields of the base class that are initialized using the derived constructor 当我在类的构造函数中声明并初始化它们时,为什么我的字段被初始化为 null 或默认值零? - Why are my fields initialized to null or to the default value of zero when I've declared and initialized them in my class' constructor? 在构造函数中初始化的模拟依赖项 - Mocking dependency initialized in constructor 未在默认构造函数中初始化的变量 - Variable not initialized in default constructor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM