Use Lombok Introduction (common comment)

lombok is a very magical java class libraries, will use the automatically generated annotations in java Bean annoying Getter, Setter, can automatically generate a logger, ToString, HashCode, Builder and other java
function in line with the characteristics of a function or design patterns, can make you java Bean simpler, more beautiful. lombok thought very advanced, it allows us to omit the tedious boilerplate code, do not spend too much time on repetitive code, an idea which is also Java language evolution will inevitably arise, take 20% of the time to do 80% thing. Here's a look at the specific usage of lombok.

@Data

@Data is a very convenient annotation, and it @ToString, , @EqualAndHashCode, @Getter/@Setterand @RequiredArgsConstructorare bound together. In other words, @ Data generated generally simple POJO (Plain Old Java Objects) and all the boilerplate code associated with the bean, for example: Get all the properties, set all non-inherited properties, to adapt to achieve toString, equals and hashcode of, initializing all the constructor final properties, and all without the use of @NonNulla non-final fields labeled initialization procedure, to ensure that the field is never null.

@Data use @toString as implied in the class, as @EqualAndHashCode, @Getter, @Setter and @RequiredArgsConstructor comments. @Data = @Getter + @Setter + @ToString + @EqualsAndHashCode + @RequiredArgsConstructor

However, @ Data can not set the parameters of these annotations, such as callSuper, includeFieldNames and exclude

If you need to set a non-default values ​​for these parameters in any just explicitly add these comments;

All generated getters / setters are public by default, in order to cover the access level, with explicit @Setter @Getter annotation fields or classes to annotations. You can use this comment (by binding AccessLevel.NONE) to prohibit the use of a getter or setter.

Use all transientthe fields marked will not be treated as hashcode and equals. Completely skip all static fields (without regard to any method of generating and does not create a setter / getter for them).

If the class already contains methods and any method commonly generated with the same name and count parameters, this method is not generated, and will not issue a warning or error. For example: If you use equals marked a method, it will not generate equals method, even though technically, because of the different types of parameters, it may be a completely different approach. The same rule applies to the constructor (any explicit constructors will generate a stop @Data), and toString, equals, and all getter and setter. You can use the @ lombok.experimental.Tolerate mark any constructor or method, to hide them in lombok

E.g:

import lombok.AccessLevel;
import lombok.Data;
import lombok.Setter;
import lombok.ToString;

@Data
public class DataExample {

    private final String name;

    @Setter(AccessLevel.PACKAGE)
    private int age;

    private double score;

    private String[] tags;

    @ToString(includeFieldNames = true)
    @Data(staticConstructor = "of")
    public static class Exercise<T> {
        private final String name;
        private final T value;
    }

}

It is equivalent to the following examples do not lombok:

import java.util.Arrays;

public class DataExample {
  private final String name;
  private int age;
  private double score;
  private String[] tags;
  
  public DataExample(String name) {
    this.name = name;
  }
  
  public String getName() {
    return this.name;
  }
  
  void setAge(int age) {
    this.age = age;
  }
  
  public int getAge() {
    return this.age;
  }
  
  public void setScore(double score) {
    this.score = score;
  }
  
  public double getScore() {
    return this.score;
  }
  
  public String[] getTags() {
    return this.tags;
  }
  
  public void setTags(String[] tags) {
    this.tags = tags;
  }
  
  @Override public String toString() {
    return "DataExample(" + this.getName() + ", " + this.getAge() + ", " + this.getScore() + ", " + Arrays.deepToString(this.getTags()) + ")";
  }
  
  protected boolean canEqual(Object other) {
    return other instanceof DataExample;
  }
  
  @Override public boolean equals(Object o) {
    if (o == this) return true;
    if (!(o instanceof DataExample)) return false;
    DataExample other = (DataExample) o;
    if (!other.canEqual((Object)this)) return false;
    if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false;
    if (this.getAge() != other.getAge()) return false;
    if (Double.compare(this.getScore(), other.getScore()) != 0) return false;
    if (!Arrays.deepEquals(this.getTags(), other.getTags())) return false;
    return true;
  }
  
  @Override public int hashCode() {
    final int PRIME = 59;
    int result = 1;
    final long temp1 = Double.doubleToLongBits(this.getScore());
    result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode());
    result = (result*PRIME) + this.getAge();
    result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32));
    result = (result*PRIME) + Arrays.deepHashCode(this.getTags());
    return result;
  }
  
  public static class Exercise<T> {
    private final String name;
    private final T value;
    
    private Exercise(String name, T value) {
      this.name = name;
      this.value = value;
    }
    
    public static <T> Exercise<T> of(String name, T value) {
      return new Exercise<T>(name, value);
    }
    
    public String getName() {
      return this.name;
    }
    
    public T getValue() {
      return this.value;
    }
    
    @Override public String toString() {
      return "Exercise(name=" + this.getName() + ", value=" + this.getValue() + ")";
    }
    
    protected boolean canEqual(Object other) {
      return other instanceof Exercise;
    }
    
    @Override public boolean equals(Object o) {
      if (o == this) return true;
      if (!(o instanceof Exercise)) return false;
      Exercise<?> other = (Exercise<?>) o;
      if (!other.canEqual((Object)this)) return false;
      if (this.getName() == null ? other.getValue() != null : !this.getName().equals(other.getName())) return false;
      if (this.getValue() == null ? other.getValue() != null : !this.getValue().equals(other.getValue())) return false;
      return true;
    }
    
    @Override public int hashCode() {
      final int PRIME = 59;
      int result = 1;
      result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode());
      result = (result*PRIME) + (this.getValue() == null ? 43 : this.getValue().hashCode());
      return result;
    }
  }
}

@NonNull

You can @NonNullgenerate null constructor method or - check

If you lombok or constructor to generate the overall process (e.g. @Data), Lombok always referred to as the upper field is generally regarded as the annotations @NonNull check signal generating null. But now, using their own parameters on lombok @ lombok.NonNull will lead to only insert null-check statement in your own method or constructor.

Null - Check statement looks like the following statement

if(param == null){
  throw new NullPointerException("param is marked @NonNull but is null")
}

This statement will judge sentenced empty at the beginning of the method

public class NonNullExample {

    @Getter
    private String name;

    public NonNullExample(@NonNull String name){
        this.name = name;
    }
}

This sentence plus @NonNull empty code is equivalent to the following code

import lombok.NonNull;

public class NonNullExample {
  private String name;
  
  public NonNullExample(@NonNull String name) {
    if (name == null) {
      throw new NullPointerException("name is marked @NonNull but is null");
    }
    this.name = name;
  }
}

@Getter & @Setter

You can use @Getter and @Setter automatically generate any getter / setter.

The default getter only returns the name of the field, if the field name is foo, then returns getFoo (), if the field type is boolean, return isFoo (). If the field is foo, then return the default setFoo setter, and the type is void, and with one and the same field as the property parameter, the attribute field is used for this assignment.

Unless you specify access levels AccessLevel, otherwise Getter / Setter generation methods are public by default scope. AccessLevel access levels are PUBLIC, PROTECTED, PACKAGE, and PRIVATE.

You can also use @Getter / @Setter in the class, in this case, it will generate get and set methods in the class of all non-static properties

You can also disable any generation get and set methods by setting AccessLevel.NONE. This will @ annotation Data, @ Getter / @Setter failure.

public class GetterSetterExample {

    @Setter
    @Getter
    private int age = 10;

    @Setter(AccessLevel.PROTECTED)
    private String name;

    @Getter(AccessLevel.PRIVATE)
    private String high;
}

Equivalent to

public class GetterSetterExample {

  private int age = 10;

  private String name;
  
  private String high;
  
  public int getAge() {
    return age;
  }
  
  public void setAge(int age) {
    this.age = age;
  }
  
  protected void setName(String name) {
    this.name = name;
  }
  
  private String getHigh(){
    return high;
  }
}

@ToString

@ToString annotation is used to replace the realization generating toString () method, by default, it will print your name and the class of each field sequentially, separated by commas.

By setting includeFieldNames = trueenables toString () method printing attribute value and name of each field.

By default, all non-static properties have been printed, if you want to exclude certain fields, then you need to set @ToString.Exclude, or you can specify ToString(onlyExplicitlyIncluded = true)which fields you want to use to specify. Then use @ ToString.Includeeach field to include tag.

By setting callSuperto true, the output of the superclass implementation toString comprises the output. Please note, java.lang.Object is toString () implementation does not make any sense, so you may not do this unless you want to extend another class.

You can also include an output method invoked toString in. Examples comprising only (non-static) method without parameters, for which use the @ ToString.Includetag method.

You can use @ToString.Include(name =“some other name”)the name change is used to identify members and can @ ToString.Include(rank = -1)change the membership of the print order. No members defined default level 0, the high priority level member to be printed, the printing members of the same priority in the order they appear in the source file.

@ToString
public class ToStringExample {

  // 静态属性不会包含
  private static final int STATIC_VAR = 10;
  private String name;
  private String[] tags;
  private Shape shape = new Square(5, 10);

  // 排除指定字段不会被 toString 打印
  @ToString.Exclude
  private int id;

  public String getName() {
    return this.name;
  }

  // callSuper 表示是否扩展父类的 toString(), 
  // includeFieldNames 表示是否包含属性名称
  @ToString(callSuper = true, includeFieldNames = true)
  public static class Square extends Shape{
    private final int width, height;

    public Square(int width, int height) {
      this.width = width;
      this.height = height;
    }
  }

  public static class Shape {}
}

Test the example above

ToStringExample toStringExample = new ToStringExample();
System.out.println(toStringExample);

Output follows

ToStringExample(name=null, tags=null, shape=ToStringExample.Square(super=com.project.lombok.ToStringExample$Square@1b9e1916, width=5, height=10))
  • Comment out callSuper = to true , the test results are as follows
ToStringExample(name=null, tags=null, shape=ToStringExample.Square(width=5, height=10))

As can be seen from the output, if the parent class is not extended, does not output the internal class information about the Shape, callSuper default is false

  • Comment out includeFieldNamesthe test results will not change, so the default value is true includeFieldNames
  • Change includeFieldNames = false, the test results are as follows
ToStringExample(name=null, tags=null, shape=ToStringExample.Square(super=com.project.lombok.ToStringExample$Square@1b9e1916, 5, 10))

As can be seen from the output, if set includeFieldNames = false, the field names are not output in Shape information.

The above examples of modifications with @ToString annotation is equivalent to the following code

import java.util.Arrays;

public class ToStringExample {
  private static final int STATIC_VAR = 10;
  private String name;
  private Shape shape = new Square(5, 10);
  private String[] tags;
  private int id;
  
  public String getName() {
    return this.getName();
  }
  
  public static class Square extends Shape {
    private final int width, height;
    
    public Square(int width, int height) {
      this.width = width;
      this.height = height;
    }
    
    @Override public String toString() {
      return "Square(super=" + super.toString() + ", width=" + this.width + ", height=" + this.height + ")";
    }
  }
  
  @Override public String toString() {
    return "ToStringExample(" + this.getName() + ", " + this.shape + ", " + Arrays.deepToString(this.tags) + ")";
  }
  
  public static class Shape {}
}

@EqualsAndHashCode

Any class definitions can be @EqualsAndHashCodemarked, let lombok generated for equalsand hashCodemethods. By default, it will be used in non-static, non-transient fields marked, but you can @EqualsAndHashCode.Includeor @EqualsAndHashCode.Excludemarker type members to modify which fields to use. Alternatively, you can mark them to accurately specified field or you wish to use a method by using @ EqualsAndHashCode.Include using @EqualsAndHashCode (onlyExplicitlyIncluded = true).

If @EqualsAndHashCode applied to extend another class, this feature will become very dangerous. Generally speaking, the class generated automatically equalsand hashcodeis not a good selection method, because the super class also defines fields that need equals / hashCode method. By setting callSuper to true, and may comprise equals hachcode superclass generated in the process. For hashCode, the result super.hashCode includes a hash algorithm for equals, if the super class implements think it is not equal to the passed in object, generated method returns false. Please note that not all equals realization can properly handle this situation. However, lombok generated equalsimplemented to handle this correctly.

If you do not extend the class (only extend any java.lang.Objectclass) when the callSuper set to true will be prompted to compile error because lombok will generate the equals()method and hashCode()achieve convert inherited from Object: only the same Object object equal to each other and have the same hashCode . When not set callSuper when you inherit from other classes warnings to true, because unless the parent class is not the same attributes, lombok not consider implementing field generated super class declaration for you. You need to write your own implementation class or rely callSuper tool. You can also use the lombok.equalsAndHashCode.callSuperconfiguration key.

Below is an example

@EqualsAndHashCode
public class EqualsAndHashCodeExample {

    private transient int transientVar = 10;
    private String name;
    private double score;
    @EqualsAndHashCode.Exclude private Shape shape = new Square(5,10);
    private String[] tags;
    @EqualsAndHashCode.Exclude private int id;

    public String getName() {
        return name;
    }

    @EqualsAndHashCode(callSuper = true)
    public static class Square extends Shape {
        private final int width,height;

        public Square(int width,int height){
            this.width = width;
            this.height = height;
        }
    }

    public static class Shape {}
}

@NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor

lombok three annotations generated constructor look with instructions for their use and the following examples

@NoArgsConstructorWill generate a constructor with no arguments, if finalmodified field is not initialized and modified field for the final, then simply use @NoArgsConstructor notes will be prompted to compile errors

Proposed changes: specify a property @NoArgsConstructor @NoArgsConstructor (= Force to true) , Lombok adds final field default initial values for the above, since id is of type int id so that the initial value of 0, the different types of fields similar the initial value as well as false / null / 0the specific structure of Java, such as hibernate and services provided constructor interface requires no arguments. This annotation @Data main function in combination with other configurations or generated with the use of annotations.

Here is a place to note: @NonNull Do not use with @NoArgsConstructor

@NoArgsConstructor
@Getter
public class NoArgsConstructorExample {
    private  Long id ;
    private @NonNull String name;
    private Integer age;

    public static void main(String[] args) {
        System.out.println(new NoArgsConstructorExample().getName());
    }
}

The output is null, so if you have @NonNullmodified variable members not to use the @NoArgsConstructormodified class

@RequiredArgsConstructorIt will be generated with a constructor parameter for each field that requires special handling. All uninitialized final field will get a parameter, and any field labeled @NonNull will get a parameter. These fields are not initialized where they are declared. For these marked @NonNull field generates a special null compilation checking. If the flag is @NonNullparameter field is null, then the constructor will throw NullPointerException . Order of the fields match the parameters in the display order of the class.

For example the following example, only @NonNull and final modified field will be added to the constructor

@RequiredArgsConstructor
public class RequiredArgsConstructorExample {

    @NonNull
    private int id;
    private final String name;
    private boolean human;
    
}

Results generated something like this

public class RequiredArgsConstructorExample {
    @NonNull
    private int id;
    private final String name;
    private boolean human;

    public RequiredArgsConstructorExample(@NonNull int id, String name) {
        if (id == null) {
            throw new NullPointerException("id is marked @NonNull but is null");
        } else {
            this.id = id;
            this.name = name;
        }
    }
}

@AllArgsConstructor: @AllArgsConstructor generates a constructor with one parameter for each field in the class. Fields marked with @NonNull these parameters will result in an empty check.

@AllArgsConstructor
public class AllArgsConstructorExample {

    private int id;
    private String name;
    private int age;

}

It corresponds to the following code automatically generated

public AllArgsConstructorExample(int id, String name, int age) {
    this.id = id;
    this.name = name;
    this.age = age;
}

Each of these annotations allow the use of alternative forms, are always generated private constructor, and generates additional static factory method comprising private constructor function, this mode is enabled by providing a value for the annotation staticname, @RequiredArgsConstructor (= staticname "of"). Look at the following example

@RequiredArgsConstructor(staticName = "of")
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class ConstructorExample<T> {
  private int x, y;
  @NonNull private T description;
  
  @NoArgsConstructor
  public static class NoArgsExample {
    @NonNull private String field;
  }
}

It will become

public class ConstructorExample<T> {
  private int x, y;
  @NonNull private T description;
  
  private ConstructorExample(T description) {
    if (description == null) throw new NullPointerException("description");
    this.description = description;
  }
  
  public static <T> ConstructorExample<T> of(T description) {
    return new ConstructorExample<T>(description);
  }
  
  @java.beans.ConstructorProperties({"x", "y", "description"})
  protected ConstructorExample(int x, int y, T description) {
    if (description == null) throw new NullPointerException("description");
    this.x = x;
    this.y = y;
    this.description = description;
  }
  
  public static class NoArgsExample {
    @NonNull private String field;
    
    public NoArgsExample() {
    }
  }
}

No public to provide quality information and CSDN free download Java permissions, you are welcome to follow me

Reference article:

https://www.hellojava.com/a/74973.html

https://www.projectlombok.org/features/constructor

Guess you like

Origin www.cnblogs.com/cxuanBlog/p/11272948.html