Java动态获取集方法

时间:2015-09-19 16:03:40

标签: java methods setter getter getter-setter

您好我想知道如何在我正在处理的java程序中创建最动态的get set方法?该程序有多个字段,每个字段都需要有自己的get和set方法,但我只想要一个get set方法,可以获取和设置我想要的类中的任何字段。

package kalsi;

public class ContestantInformation {
    String firstName, lastName, city, province, postalCode, streetName, streetNumber, phoneNum, birthDate;

    public ContestantInformation() {    
    }

    public ContestantInformation(String firstName, String lastName, int streetNumber, String streetName, String city,
            String province, String postalCode, int phoneNum, int birthDate) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.birthDate = "" + birthDate;
        this.streetNumber = "" + streetNumber;
        this.streetName = streetName;
        this.city = city;
        this.postalCode = postalCode;
        this.phoneNum = "" + phoneNum;
    }

    public void setName(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

}

1 个答案:

答案 0 :(得分:3)

您可以使用IDE生成getter/setter方法。如果你正在使用eclipse,那么你可以通过转到 Source>生成方法来实现。

或者您也可以动态使用lombok生成getter setter方法。在这种情况下,您甚至不需要编写getter/setter方法。看一下例子 -

import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

public class Person {

   @Getter @Setter private String name;
   @Getter @Setter private int age = 10;
 }