如何使用lombok生成标准访问器和流畅的访问器?

时间:2016-04-12 05:17:31

标签: java accessor lombok

我试过了。

@lombok.Getter
@lombok.Setter
@lombok.Accessors(chain = true, fluent = true)
private String prop;

@Accessor优先,getPropsetProp未生成。

如何让它产生这个?

public String getProp() {
    return prop;
}
public String prop() {
    //return prop;
    return getProp(); // wow factor
}
public void setProp(String prop) {
    this.prop = prop;
}
public Some prop(String prop) {
    //this.prop = prop;
    setProp(prop); // wow factor, again
    return this;
}

3 个答案:

答案 0 :(得分:9)

不幸的是,这是不可能的。您需要实现自己的getter和setter,并添加@Getter @Setter和@Accessors(fluent = true)注释来实现此目的。

public class SampleClass {
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int id(){
        return id;
    }

    public void id(int id){
        this.id=id;
    }
}

结果你会得到类:

Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
    Uri selectedImageUri = data.getData();
    mImagePath = getPath(selectedImageUri);
    mBitmap = BitmapFactory.decodeFile(mImagePath);
    mProfilePic.setImageBitmap(mBitmap);
}}

答案 1 :(得分:7)

我担心你不能。

来自doc(强调是我的):

  

public AutoScrollList(TaskFragment fragment, ListView passengerList) { this.fragment = fragment; this.passengerList = passengerList; } public void Run() { Console.WriteLine("*** Runnable starting"); int listViewSize = this.passengerList.Adapter.Count; for (int index = 0; index < listViewSize; index++) { this.passengerList.SmoothScrollToPositionFromTop(this.passengerList.LastVisiblePosition + 100, 0, 100000); } } 注释用于配置 lombok如何生成并查找getter和setter。

因此@Accessors不生成任何内容,只是配置@Accessors@Getter的方法。

如果你真的想要流畅的常规的getter / setter,你可以添加(手动)常规的getter / setter,并将它们委托给流利的。

答案 2 :(得分:0)

@Accessors(chain = true)
@Setter @Getter
public class Person {
    private String firstName;
    private String lastName;
    private int height;
}

....

@Test
public void testAccessors() {
    Person person = new Person();

    person.setFirstName("Jack")
        .setLastName("Bauer")
        .setHeight(100);

    assertEquals("Jack", person.getFirstName());
    assertEquals("Bauer", person.getLastName());
    assertEquals(100, person.getHeight());
}