Lombok之@Getter/@Setter使用

x33g5p2x  于2021-12-25 转载在 其他  
字(5.8k)|赞(0)|评价(0)|浏览(351)

一. 为什么要用@Getter/@Setter?

在创建实体类的时候,通常我们要为成员变量(成员变量分为类变量和实例变量)创建getter和setter方法,这些方法千篇一律。下面是Student类的getter和setter方法。

public class Student {

    private String name;

    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

可以看到,setter方法的形参类型跟该方法所对应的成员变量类型相同,每个setter方法的访问控制符,返回类型,方法体都是一样的。getter方法的返回类型跟该方法所对应的成员变量类型相同,每个getter方法的访问控制符,形参,方法体都是一样的。这些类似的代码结构占据了一个实体类大量的篇幅,而且开发者和维护者都不关心这些方法的实现。所以,我们需要这样的一种工具既能让实体类拥有getter和setter方法,又不占据代码的篇幅。它就是lombok中的@Getter和@Setter注解。

二. @Getter/@Setter如何使用?

@Getter和@Setter注解使用很简单,针对上面的Student类,我们对它使用@Getter和@Setter注解。

@Getter
@Setter
public class Student {

    private String name;

    private int age;
}

在Studnet类上加上@Getter和@Setter即可。

当然,你可以将注解加需要生成getter和setter方法的成员变量上。有同学可能会问,加在了类上,但是要某个成员变量生成特殊getter和setter怎么办?这个问题,可以直接手动编写该变量的getter和sette方法,当lombok检测到你已经为该变量编写了相应的getter和setter方法后,就不会再自动生成了。
将项目使用maven编译后,再打开Student.class文件。

三. @Getter/@Setter源码

package lombok;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** * Put on any field to make lombok build a standard getter. * <p> * Complete documentation is found at <a href="https://projectlombok.org/features/GetterSetter">the project lombok features page for &#64;Getter and &#64;Setter</a>. * <p> * Even though it is not listed, this annotation also has the {@code onMethod} parameter. See the full documentation for more details. * <p> * Example: * <pre> * private &#64;Getter int foo; * </pre> * * will generate: * * <pre> * public int getFoo() { * return this.foo; * } * </pre> * <p> * This annotation can also be applied to a class, in which case it'll be as if all non-static fields that don't already have * a {@code @Getter} annotation have the annotation. */
@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.SOURCE)
public @interface Getter {
	/** * If you want your getter to be non-public, you can specify an alternate access level here. * * @return The getter method will be generated with this access modifier. */
	lombok.AccessLevel value() default lombok.AccessLevel.PUBLIC;
	
	/** * Any annotations listed here are put on the generated method. * The syntax for this feature depends on JDK version (nothing we can do about that; it's to work around javac bugs).<br> * up to JDK7:<br> * {@code @Getter(onMethod=@__({@AnnotationsGoHere}))}<br> * from JDK8:<br> * {@code @Getter(onMethod_={@AnnotationsGohere})} // note the underscore after {@code onMethod}. * * @return List of annotations to apply to the generated getter method. */
	AnyAnnotation[] onMethod() default {};
	
	boolean lazy() default false;
	
	/** * Placeholder annotation to enable the placement of annotations on the generated code. * @deprecated Don't use this annotation, ever - Read the documentation. */
	@Deprecated
	@Retention(RetentionPolicy.SOURCE)
	@Target({})
	@interface AnyAnnotation {}
}

从上面的类注释(第十一行),我们可以看到完整的文档地址为:https://projectlombok.org/features/GetterSetter
元注解:从@Target({ElementType.FIELD, ElementType.TYPE}),我们可以知道这个注解可以应用在ElementType.FIELD和ElementType.TYPE上;@Retention(RetentionPolicy.SOURCE)表明注解的保留策略——只存在于源码中,编译后的class文件将不会出现。对于ElementType和RetentionPolicy枚举类不是很清楚的同学,先去补补课。

注解属性:value表明生成的方法的访问控制符,这个注解属性可以指定方法的访问控制符是public,还是private,或protected等等(更多内容参考lombok.AccessLevel枚举类)。
AnyAnnotation加了@Deprecated注解,表明它已经被弃用了,开发者不用关心它,目前还存在于源码中,只是作为一个占位符注释服务于onMethod属性。
onMethod注解属性参考Lombok实验室之onX使用。
lazy注解属性比较特殊,不是很常用,但是对于特殊的情况下很有效果。请参考Lombok之@Getter(lazy = true)使用。

package lombok;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** * Put on any field to make lombok build a standard setter. * <p> * Complete documentation is found at <a href="https://projectlombok.org/features/GetterSetter">the project lombok features page for &#64;Getter and &#64;Setter</a>. * <p> * Even though it is not listed, this annotation also has the {@code onParam} and {@code onMethod} parameter. See the full documentation for more details. * <p> * Example: * <pre> * private &#64;Setter int foo; * </pre> * * will generate: * * <pre> * public void setFoo(int foo) { * this.foo = foo; * } * </pre> * * <p> * This annotation can also be applied to a class, in which case it'll be as if all non-static fields that don't already have * a {@code Setter} annotation have the annotation. */
@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.SOURCE)
public @interface Setter {
	/** * If you want your setter to be non-public, you can specify an alternate access level here. * * @return The setter method will be generated with this access modifier. */
	lombok.AccessLevel value() default lombok.AccessLevel.PUBLIC;
	
	/** * Any annotations listed here are put on the generated method. * The syntax for this feature depends on JDK version (nothing we can do about that; it's to work around javac bugs).<br> * up to JDK7:<br> * {@code @Setter(onMethod=@__({@AnnotationsGoHere}))}<br> * from JDK8:<br> * {@code @Setter(onMethod_={@AnnotationsGohere})} // note the underscore after {@code onMethod}. * * @return List of annotations to apply to the generated setter method. */
	AnyAnnotation[] onMethod() default {};
	
	/** * Any annotations listed here are put on the generated method's parameter. * The syntax for this feature depends on JDK version (nothing we can do about that; it's to work around javac bugs).<br> * up to JDK7:<br> * {@code @Setter(onParam=@__({@AnnotationsGoHere}))}<br> * from JDK8:<br> * {@code @Setter(onParam_={@AnnotationsGohere})} // note the underscore after {@code onParam}. * * @return List of annotations to apply to the generated parameter in the setter method. */
	AnyAnnotation[] onParam() default {};
	
	/** * Placeholder annotation to enable the placement of annotations on the generated code. * @deprecated Don't use this annotation, ever - Read the documentation. */
	@Deprecated
	@Retention(RetentionPolicy.SOURCE)
	@Target({})
	@interface AnyAnnotation {}
}

@Setter注解属性可参照@Getter的解释理解。其中,onParam注解属性参考Lombok实验室之onX使用。

四. 特别说明

本文已经收录在Lombok注解系列文章总览中,并继承上文中所提的特别说明。
源码地址:gitee

相关文章