Skip to content

Instantly share code, notes, and snippets.

@MartinKnopf
Created June 28, 2013 22:49
Show Gist options
  • Save MartinKnopf/5888757 to your computer and use it in GitHub Desktop.
Save MartinKnopf/5888757 to your computer and use it in GitHub Desktop.
how to init fields of a java class using annotations
@Retention(value=RUNTIME)
@Target({ElementType=FIELD})
public @interface DefaultIfNUll {
String stringValue();
int intValue();
boolean booleanValue();
byte byteValue();
short shortValue();
long longValue();
float floatValue();
double doubleValue();
}
//...
public class MyClass {
@DefaultIfNull(stringValue="some value") private String field1;
@DefaultIfNull(intValue=123) private int field2;
public void setField1(Object field1) {
this.field1 = field1;
}
}
//...
public class Defaulter {
public static void initNullFields(Object obj) {
for(Field field in obj.getClass().getFields()) {
if(field.get(obj) != null) {
DefaultIfNull dflt = field.getAnnotation(DefaultIfNull.class);
if(anno != null) {
// handle fields type
field.set(obj, dflt.stringValue())
}
}
}
}
}
//...
MyClass obj = new MyClass();
obj.setField1(null);
Defaulter.initNullFields(obj);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment