简体   繁体   English

实例变量的构造方法初始化

[英]Constructor initialization of instance variables

If I have something like the code below as a constructor, is there a simple, shorthand way to do all the instance variable initializations in one line if all their names are the same as the parameter names? 如果我将下面的代码用作构造函数,如果所有实例变量的名称都与参数名称相同,是否有一种简单快捷的方法可以在一行中完成所有实例变量的初始化?

private Quiz(int id, String name, int creatorId, Date timeCreated,
        int categoryId, boolean randomOrder, boolean multiPage,
        boolean immediateCorrection, boolean allowPractice) {
    this.id = id;
    this.name = name;
    this.creatorId = creatorId;
    this.timeCreated = timeCreated;
    this.categoryId = categoryId;
    this.randomOrder = randomOrder;
    this.multiPage = multiPage;
    this.immediateCorrection = immediateCorrection;
    this.allowPractice = allowPractice;
}

Unfortunately there is no simpler way to initialize instance variable - you have to write such initialization code in a constructor. 不幸的是,没有简单的方法来初始化实例变量-您必须在构造函数中编写此类初始化代码。

However all modern IDE (like IntelliJ IDEA, Eclipse, etc.) can generate such constructors automatically based on instance variables, so you don't have to write such code manually. 但是,所有现代IDE(例如IntelliJ IDEA,Eclipse等)都可以根据实例变量自动生成此类构造函数,因此您不必手动编写此类代码。 (For instance in IntelliJ IDEA press Alt+Insert, choose Constructor, select variables which you need and the constructor code will be generated). (例如,在IntelliJ IDEA中,按Alt + Insert,选择“构造函数”,选择所需的变量,然后将生成构造函数代码)。

Also, if you have so many variables which you need to pass and initialize in the constructor (and especially if not all of them are required) - consider to use patter Builder (unfortunately you will have to write even more code!). 另外,如果您有太多需要在构造函数中传递和初始化的变量(特别是如果不需要所有变量),请考虑使用patter Builder(不幸的是,您将不得不编写更多代码!)。 Here is an example how to implement Builder: http://www.javacodegeeks.com/2013/01/the-builder-pattern-in-practice.html 这是一个如何实现Builder的示例: http : //www.javacodegeeks.com/2013/01/the-builder-pattern-in-practice.html

No there is not, but you should refer to the builder approach since there are a lot of parameters / arguments to the constructor in there. 不,没有,但是您应该参考builder方法,因为那里有很多构造函数的parameters / arguments

The builder would make the object creation readable, less error prone and assists in thread safety as well. builder将使对象创建易于阅读,不易出错,并有助于线程安全。

Take a look at When would you use the Builder Pattern? 看看何时使用构建器模式? for details and samples. 有关详细信息和样品。

Project Lombok has a series of class annotations you can add to your class that will generate constructors of the kind you describe. Lombok项目具有一系列类注释,您可以将其添加到类中,这些注释将生成您描述的那种构造函数。 Take a look at @NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor here: 在这里查看@ NoArgsConstructor,@ RequiredArgsConstructor和@AllArgsConstructor:

https://projectlombok.org/features/index.html https://projectlombok.org/features/index.html

The other annotations available in Lombok are similarly magical for removing boilerplate from your classes, take a look. Lombok中可用的其他注释对于从类中删除样板同样具有魔力,请看一下。 Lombok is fantastic and IntelliJ Idea has good plugin support for debugging and testing Lombok-annotated classes. Lombok非常棒,IntelliJ Idea对调试和测试带Lombok注释的类具有良好的插件支持。

You can use a factory method that acts like a constructor, but actually returns an anonymous subclass of the main class. 您可以使用行为类似于构造函数的工厂方法,但实际上会返回主类的匿名子类。 The methods of the anonymous subclass can access the factory method parameters as long as they are declared final. 只要声明为final,匿名子类的方法就可以访问工厂方法参数。 So this technique can only be used for fields that never change. 因此,此技术只能用于永远不变的字段。

import java.util.Date;

abstract class Quiz{

  static Quiz newQuiz(final int id, final String name, final int creatorId, final Date timeCreated,
                      final int categoryId, final boolean randomOrder, final boolean multiPage,
                      final boolean immediateCorrection, final boolean allowPractice) {

    // Return anonymous subclass of Quiz
    return new Quiz(){

      @Override
      public String someMethod() {
        // Methods can access newQuiz parameters
        return name + creatorId + categoryId + timeCreated;
      }

      @Override
      public boolean someOtherMethod() {
        // Methods can access newQuiz parameters
        return randomOrder && multiPage && allowPractice;
      }

    };
  }

  public abstract String someMethod();
  public abstract boolean someOtherMethod();


  public static void main(String[] args) {
    Quiz quiz = Quiz.newQuiz(111, "Fred", 222, new Date(), 333, false, true, false, true);
    System.out.println(quiz.someMethod());
    System.out.println(quiz.someOtherMethod());
  }

}

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

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