Zarathustra
Zarathustra

Reputation: 2943

Correct getter and setter for a JavaBean

I have a class which is used as a DTO I am wondering what the correct naming for the getter and setter methods is.

Current code:

public class NiceClass {
    private String PE_DATAB;

    public void setPE_DATAB(final String PE_DATAB) {
        this.PE_DATAB = PE_DATAB;
    }
}

But after reading the JavaBeansSpec my best guess is:

public void setPe_DATAB(final String PE_DATAB) {
    this.PE_DATAB = PE_DATAB;
}

What is the correct naming for the setter method above for the variable PE_DATAB?

I can not rename the variable!

Upvotes: 0

Views: 4151

Answers (3)

YoungHobbit
YoungHobbit

Reputation: 13402

Adding Setter and Getter Methods. The getter and setter method should contains the name of the variable they are returning or setting. You can use the above mentioned tutorial from Java Documentation. The standard for getter and setter are same irrespective of application. Please read about Java Pojo.

If you are using any IDE for development, then your IDE can generate getter and setter without any efforts.

Upvotes: 0

Tunaki
Tunaki

Reputation: 137064

public class NiceClass {
    private String PE_DATAB;

    public void setPE_DATAB(final String PE_DATAB) {
        this.PE_DATAB = PE_DATAB;
    }
}

is the correct code according to the JavaBeans specification.

You can check that it is correct with the following code:

public class Main {

    public static void main(String[] args) throws Exception {
        BeanInfo info = Introspector.getBeanInfo(NiceClass.class);
        System.out.println("Setter: " + info.getPropertyDescriptors()[0].getWriteMethod());
        // prints "Setter: public void Main$NiceClass.setPE_DATAB(java.lang.String)"
        System.out.println("Name of variable: " + info.getPropertyDescriptors()[0].getName());
        // prints "Name of variable: PE_DATAB"
    }

    public class NiceClass {

        private String PE_DATAB;

        public void setPE_DATAB(String PE_DATAB) {
            this.PE_DATAB = PE_DATAB;
        }

    }

}

This is defined in section 8.3.1 of the JavaBean specification. Quoting:

By default, we use design patterns to locate properties by looking for methods of the form:

public <PropertyType> get<PropertyName>();

public void set<PropertyName>(<PropertyType> a);

If we discover a matching pair of get<PropertyName> and set<PropertyName> methods that take and return the same type, then we regard these methods as defining a read-write property whose name will be <propertyName>.

Upvotes: 1

Karthik R
Karthik R

Reputation: 5786

You can check with your IDE quicker for this. However this is the getter and setter any framework will invoke:

private String PE_DATAB;

public String getPE_DATAB() {
    return PE_DATAB;
}

public void setPE_DATAB(String PE_DATAB) {
    this.PE_DATAB = PE_DATAB;
}

Please note that as you know, PE_DATAB is not a naming convention to follow.

Upvotes: 1

Related Questions