Populate default values through reflection in java
I have a complex object hierarchy that has a couple of extends.
I am looking for a library that can reflectively insert default values on all fields.
For instance:
class Person {
String name;
Color color;
List<Clothes> clothes;
}
class Child extends Person {
Sibling sibling;
}
class Foo {
Person person;
Child child;
}
I would like a library that take an object as parameter, in this case the Foo
class, and then reflectively insert default values (even better if I can define default values) on all fields. Also all maps,list,sets etc should get a new
I have looked at BeanUtils, but to my knowledge, it doesn't support exactly what I am looking for.
NB: These are just examples, and my objects are much more complex and big. They have many objects, and each object has many objects and so on. Both wit开发者_C百科h maps, lists etc.
Is it maybe better to combine some libraries like BeanUtils and Google Guava and make it my own?
It should be fairly simple to do in one method provided you have the structure already built (in when case setting them as you build is a more logical approach)
If you know the default values in advance, why not just set them in the class? (i.e. default, default values ;)
Is there much value in setting a default name for a person (other than null) Can you give an example of where you would want to specify the default value dynamically?
Personally I would just try to use normal java constructors, and/or getters and setters etc. However from the question I'm guessing you want something that can work without knowing the exact structure of your classes.
So if you really have to do this, you could probably do something along the lines of the following:
public void setFields(Object myObject) {
Class<?> clazz = myObject.getClass();
Field[] fields = clazz.getFields();
for(Field field : fields) {
String name = field.getName();
if(name.equals("person")) {
field.set(myObject, new Person());
} else if (name.equals("color")) {
// etc...
}
}
}
精彩评论