public class ReflectionFunctions extends Object
NamedFunctions
which can easily be transformed into matchers.
As with all reflection-based code, you will not get a compile-time error if you specify the wrong name for a the method or field. However, it will at least fail fast at runtime, throwing an error as soon as you try to construct the invalid function.
Example:
// a Function<Person, String> that calls person.getFirstName()
accessor(Person.class, String.class, "getFirstName");
accessor(Person.class, String.class, "firstName"); // standard bean accessor naming is assumed
// a Function<Person, Iterable<String>> that calls person.getChildren()
iterableAccessor(Person.class, String.class, "getChildren");
// a Matcher<Person> that is equivalent to assertThat(person.getFirstName(), equalTo("Bob"))
// (the matcher will self-describe as 'firstName "Bob"')
accessor(Person.class, String.class, "getFirstName").is(equalTo("Bob"))
| Constructor and Description |
|---|
ReflectionFunctions() |
| Modifier and Type | Method and Description |
|---|---|
static <A,B> NamedFunction<A,B> |
accessor(Class<A> objectClass,
Class<B> returnClass,
String name)
Using reflection, returns a
NamedFunction that will call a zero-argument method on its target,
or get the value of a field. |
static <A,B> NamedFunction<A,Iterable<B>> |
iterableAccessor(Class<A> objectClass,
Class<B> returnElementClass,
String name)
Similar to
accessor(Class, Class, String), but for methods or fields with an Iterable type. |
public static <A,B> NamedFunction<A,B> accessor(Class<A> objectClass, Class<B> returnClass, String name)
NamedFunction that will call a zero-argument method on its target,
or get the value of a field. It will try to find the following, in order: 1. a method with the exact
name specified ("xxx()"); 2. a method with a standard bean method prefix ("getXxx()" or "isXxx()");
3. a field with the exact name specified.objectClass - class of the targetreturnClass - type of the method's return value or the field's valuename - name of the method or fieldIllegalArgumentException - if no such method/field exists or it has the wrong return typepublic static <A,B> NamedFunction<A,Iterable<B>> iterableAccessor(Class<A> objectClass, Class<B> returnElementClass, String name)
accessor(Class, Class, String), but for methods or fields with an Iterable type.
(This is separate from accessor(Class, Class, String) because parameterized types require
special handling.)objectClass - class of the targetreturnElementClass - type of the elements in the Iterable returned by the method or fieldname - name of the method or field (follows same rules as accessor)IllegalArgumentException - if no such method or field exists or it has the wrong return typeCopyright © 2017 Atlassian. All rights reserved.