You can do it with custom annotations. Here is an example:
Firstly define the annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface DefaultValue {
String defaultValue() default "";
}
The @Target
specifies the type of the Annotation
, the possible targets are:
ElementType.ANNOTATION_TYPE
ElementType.CONSTRUCTOR
ElementType.FIELD
ElementType.LOCAL_VARIABLE
ElementType.METHOD
ElementType.PACKAGE
ElementType.PARAMETER
ElementType.TYPE
Now, for instance, you have a UserName
object, that is created when a new user is created.
public class UserName {
@DefaultValue(defaultValue = "<empty>")
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public String toString() {
return "Username is: " + this.name;
}
}
The new username Object may or may not contain a name, so we annotate it with the annotation DefaultValue
, and pass the annotation the string <empty>
. Once the object is processed, it can be check whether or not the default value should be used or not:
public class CreateName {
public static void main (String [] args) throws NoSuchFieldException, SecurityException {
System.out.println(checkUserName(new UserName()));
}
public static UserName checkUserName(UserName user) throws NoSuchFieldException, SecurityException {
if (user.getName() == null) {
Field userNameField = UserName.class.getDeclaredField("name");
if (userNameField.isAnnotationPresent(DefaultValue.class)) {
Annotation ann = userNameField.getAnnotation(DefaultValue.class);
DefaultValue value = (DefaultValue) ann;
user.setName(value.defaultValue());
}
}
return user;
}
}
This is a simple example but I hope it can help you.
Note:
If you do not want to specify the default value for every field, you can also simple annotate the field like so:
@DefaultValue
private String name;
And the default value defined in the DefaultValue
class will be used (in my example, it would default to the empty string ""
)