Field
Field Manipulation using Mirror. Just to inform, field lookup is also done on
superclasses and interfaces.
Reflecting
Reflect a field by name (will return null if not found):
Class clazz;
Field f = new Mirror().on(clazz).reflect().field("fieldName");
Reflecting all fields of a class (will return an empty list if none found):
Class clazz;
List<Field> l = new Mirror().on(clazz).reflectAll().fields();
Reflecting all fields of a class that matches a Matcher<Field> (will return an empty list if none found):
Class clazz;
List<Field> l = new Mirror().on(clazz).reflectAll().fields()
.matching(new YourCustomMatcher());
You can also map your fields to other types:
Class clazz;
List<String> l = new Mirror().on(clazz).reflectAll().fields()
.mappingTo(new YourFieldToStringMapper());
Setting Values
Setting value of a static field:
Class clazz;
new Mirror().on(clazz).set().field("fieldName").withValue(value);
Setting value of an instance field:
Object target;
new Mirror().on(target).set().field("fieldName").withValue(value);
You can also pass a java.lang.reflect.Field instead of fieldName String:
Setting value of a static field:
Field aField;
Class clazz;
new Mirror().on(clazz).set().field(aField).withValue(value);
Getting Values
Getting value of a static field:
Class clazz;
Object value = new Mirror().on(clazz).get().field("fieldName");
Getting value of a instance field:
Object target;
Object value = new Mirror().on(target).get().field("fieldName");
You can also pass a java.lang.reflect.Field instead of fieldName String:
Getting value of a static field:
Field aField;
Class clazz;
Object value = new Mirror().on(clazz).get().field(aField);