Created
June 28, 2013 22:49
-
-
Save MartinKnopf/5888757 to your computer and use it in GitHub Desktop.
how to init fields of a java class using annotations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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