In eclipse you can easily create getters and setters for your classes' fields.
Before:
package main;
public class TestClass {
private String someString;
private boolean someBoolean;
}
After creating the getters (as we don't care for setters in this question):
package main;
public class TestClass {
private String someString;
private boolean someBoolean;
/**
* @return the someString
*/
public String getSomeString() {
return someString;
}
/**
* @return the someBoolean
*/
public boolean isSomeBoolean() {
return someBoolean;
}
}
But if you do not initialize the String
value getSomeString()
will return null
, meaning that if I want to work with the String
in the calling object, I have to always check if for null
first.
To avoid this I found some solutions:
- Initialize the Strings immediately at their declaration:
private String someString = "";
- Reflections
return someString == null ? someString : "";
- Using java.util.Optional
- there are probably many more ways...
While writing this question I figured out that probably for the simple String
case the first method should work best: I can easily initialize the String
s to whatever I like and am done.
The reflection approach linked above seemed okay, but a bit messy to handle
exceptions where a String
should not be initialized with the empty string.
The null check is okay but now with Java 8 the last method, employing java.util.Optional
feels like the right way to do that. I would do it like this:
public String getSomeString() {
return Optional.ofNullable(someString).orElse("");
}
Is it possible to get eclipse's code templates into creating getters like this one for Strings (or all non-primitive types) only?
The standard template used (see Project -> Properties -> Java Code Style -> Code Templates -> Code -> Getter body) is:
return ${field};
I can replace it with
return java.util.Optional.ofNullable(${field}).orElse("");
which helps for Strings - but for all other types it obviously fails. So I tried
${:import(java.util.Optional)}
return Optional.ofNullable(${field}).orElse(new ${return_type}());
which is not allowed, because Variable 'return_type' is not known.
and additionally the ${:import(java.util.Optional)}
is not solved as the help makes you believe (I assume it is because Code Templates are just a stricter subset of Templates, more or less). The first makes sense - if ${return_type}
is a primitive, this is likely to fail.
Is there a way to make it happen that eclipse generates such custom getters for me? This answer allows to create such getter for one field, but that would mean I had to do it for each field individually. Is it possible to also just have it done by Source -> Generate getters/setters (or any other similar method)?
Or do you think it's best to initialize such objects at their declaration anyway?