Method
Method Manipulation using Mirror. Just to inform, method lookup is also done on
superclasses.
Reflecting
Reflecting a method by name (will return null if not found):
Class clazz;
Method m = new Mirror().on(clazz).reflect().method("methodName").withoutArgs();
Reflect a method by arguments (will return null if not found):
Class clazz;
Method m = new Mirror().on(clazz).reflect().method("methodName")
.withArgs(String.class, Object.class);
Reflecting a uniquely named method (will return null if not found or throw
MirrorException if more than one is found):
Class clazz;
Method m = new Mirror().on(clazz).reflect().method("methodName").withAnyArgs();
Reflecting all methods of a class (will return an empty list if none found):
Class clazz;
List<Method> l = new Mirror().on(clazz).reflectAll().methods();
Reflecting all getters of a class (will return an empty list if none found):
Class clazz;
List<Method> l = new Mirror().on(clazz).reflectAll().getters();
Reflecting all setters of a class (will return an empty list if none found):
Class clazz;
List<Method> l = new Mirror().on(clazz).reflectAll().setters();
Reflecting all methods of class that matches a Matcher<Method> (will return an empty list if none found):
Class clazz;
List<Method> l = new Mirror().on(clazz).reflectAll()
.methods().matching(new YourCustomMatcher());
You can also map your methods to other types:
Class clazz;
List<String> l = new Mirror().on(clazz).reflectAll()
.methods().mappingTo(new YourMethodToStringMapper());
Invoking Methods
Invoking a static method:
Class clazz;
Object returnValue = new Mirror().on(clazz).invoke().method("methodName")
.withArgs(value1, value2);
Invoking an instance method:
Object target;
Object returnValue = new Mirror().on(target).invoke().method("methodName").withoutArgs();
You can also pass a java.lang.reflect.Method instead of a methodName String:
Invoking an instance method:
Method aMethod;
Object target;
Object returnValue = new Mirror().on(target).invoke().method(aMethod)
.withArgs(value1, value2);
Invoking a setter method:
Field field;
Object target;
new Mirror().on(target).invoke().setterFor(field).withValue(value1);
new Mirror().on(target).invoke().setterFor("fieldName").withValue(value1);
Invoking a getter method:
Field field
Object target;
Object returnValue = new Mirror().on(target).invoke().getterFor(field);
Object returnValue = new Mirror().on(target).invoke().getterFor("fieldName");