Lombok中有两个annotation, @Getter, @Setter,这两个annotation完全可以达到见名知意的效果,老规矩上代码,个人觉得知识点只有在代码中演示,然后再填以文字的描述才能让话语变得强有力。
想必你一定为写这样的代码而苦恼:
- public class GetterSetterExample {
- /**
- * Age of the person. Water is wet.
- */
- private int age = 10;
- /**
- * Name of the person.
- */
- private String name;
- @Override public String toString() {
- return String.format("%s (age: %d)", name, age);
- }
- /**
- * Age of the person. Water is wet.
- *
- * @return The current value of this person's age. Circles are round.
- */
- public int getAge() {
- return age;
- }
- /**
- * Age of the person. Water is wet.
- *
- * @param age New value for this person's age. Sky is blue.
- */
- public void setAge(int age) {
- this.age = age;
- }
- /**
- * Changes the name of this person.
- *
- * @param name The new value.
- */
- protected void setName(String name) {
- this.name = name;
- }
- }
那么这两个annotation到底能干什么呢?
- import lombok.AccessLevel;
- import lombok.Getter;
- import lombok.Setter;
- public class GetterSetterExample {
- /**
- * Age of the person. Water is wet.
- *
- * @param age New value for this person's age. Sky is blue.
- * @return The current value of this person's age. Circles are round.
- */
- @Getter @Setter private int age = 10;
- /**
- * Name of the person.
- * -- SETTER --
- * Changes the name of this person.
- *
- * @param name The new value.
- */
- @Setter(AccessLevel.PROTECTED) private String name;
- @Override public String toString() {
- return String.format("%s (age: %d)", name, age);
- }
- }
小伙伴们有没有瞬间惊呆了的感觉,是的,你没有看错, 就是这么简单的用法,让代码变得简洁明了。这时候一定有朋友会提出,我用IDE很快就能生成这些代码啊,可是如果使用了Lombok会让你的代码更加简洁,清晰,可读,这是任何能自动生成get,set方法的IDE所做不到的。
如果没有设置AccessLevel属性,则生成的默认方法为public的。如果想要使get,set方法不生效,则可以使用一个特殊的AccessLevel 选项 “NONE”。
介绍几个参数的可选值:
Lombok.accessors.chain=[true|false]
如果当前值为true, set方法返回值不会void, 为this指针
Lombok.accessors.fluent=[true|false]
如果当前值为true,则生成的方法名会和定义的变量名一致的
Lombok.accessors.prefix+=
设置生成的方法的前缀,例如设置当前值为m,则得到的方法不是getName,而是mName;
Lombok.accessors.NoIsPrefix=[true|false]
如果设置为true,则所有的Boolean方法不再是isXXX,而是getXXX();
同样给大家一点小的建议:
在使用的时候如果当前bean中包括某个方法,恰好要和生成的方法名字一样,则Lombok不会再处理生成,无论是不是两个函数的方法是重载。例如:如果类中包含String get(String anme), 则不会再为bean生成一个新的bean。
转载自: http://zhuqiuxu.iteye.com/blog/2124335