Search code examples
javajavabeans

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!


Solution

  • 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>.