Search code examples
javagetter-setter

Setting field name as URL for proper getter and setter gives Checkstyle error


may be a stupid question, but just want to ask. I have a Java class with some fields and it's getters and setters.

public class Parameters {

    private String URL;

    public String getURL() {
        return URL;
    }

    public void setURL(String uRL) {
        URL = uRL;
    }
}

Checkstyle will give error as

Name 'URL' must match pattern '^[a-z][a-zA-Z0-9]*$'.

So I changed to url and generated getters and setters with Eclipse.

public class Parameters {

    private String url;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

I want the method name to be getURL and setURL. Is it better I change the method names manually or is there any other way?

NB : In case I have to search for methods based on field names using

java.beans.BeanInfo
java.beans.IntrospectionException
java.beans.Introspector
java.beans.PropertyDescriptor

for url, it will search for only getUrl and setUrl.


Solution

  • You should write getters and setters. Or better - let your IDE generate them automatically. Otherwise you break the encapsulation.

    Optionally you can use http://projectlombok.org/ and write it like this using annotations:

    @Getter @Setter
    private String name;
    

    The code generation is done compile time.

    Have a look at This site

    Edit:-

    example:

    public class Test {
    
    protected double WIDTH;
    public double getWidTh() {
      return WIDTH;
    }
    public void setWidTh(double wIDTH) {
      WIDTH = wIDTH;
    }
    public static void main(String []args){
      Test t = new Test();
      t.setWidTh(2);
      Object c = t;
      Class klazz = c.getClass();
      try {
        for (PropertyDescriptor propertyDescriptor : Introspector
        .getBeanInfo(klazz).getPropertyDescriptors()) {
          Method m = propertyDescriptor.getReadMethod();
          if (m != null)
            System.out.println(m.invoke(c));
          }
      } catch (IllegalAccessException e) {
          e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IntrospectionException e) {
        e.printStackTrace();
    }
    }
    }