Skip to content

Commit 369a491

Browse files
Treiblesschorlegselzer
authored andcommitted
Add structification of parameter annotated field and make more dry
1 parent 4507aa4 commit 369a491

1 file changed

Lines changed: 172 additions & 70 deletions

File tree

‎src/main/java/org/scijava/param/ParameterStructs.java‎

Lines changed: 172 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11

22
package org.scijava.param;
33

4+
import java.lang.reflect.AnnotatedElement;
45
import java.lang.reflect.Field;
56
import java.lang.reflect.Modifier;
67
import java.lang.reflect.Type;
@@ -38,95 +39,59 @@ public static Struct structOf(final Class<?> type)
3839
final List<Member<?>> items = parse(type);
3940
return () -> items;
4041
}
42+
43+
public static Struct structOf(final Class<?> c, final Field f)
44+
throws ValidityException
45+
{
46+
final List<Member<?>> items = parse(c, f);
47+
return () -> items;
48+
}
4149

50+
// TODO parse methods need to be way more dry
4251
public static List<Member<?>> parse(final Class<?> type)
4352
throws ValidityException
4453
{
4554
if (type == null) return null;
4655

4756
final ArrayList<Member<?>> items = new ArrayList<>();
4857
final ArrayList<ValidityProblem> problems = new ArrayList<>();
58+
final Set<String> names = new HashSet<>();
4959

5060
// NB: Reject abstract classes.
51-
if (Modifier.isAbstract(type.getModifiers())) {
52-
problems.add(new ValidityProblem("Struct class is abstract"));
53-
}
54-
55-
final Set<String> names = new HashSet<>();
61+
checkModifiers(type.getName() + ": ", problems, type.getModifiers(), true, Modifier.ABSTRACT);
5662

5763
// Parse class level (i.e., generic) @Parameter annotations.
58-
5964
final Class<?> paramsClass = findParametersDeclaration(type);
6065
if (paramsClass != null) {
61-
final Class<?> functionalType = findFunctionalInterface(paramsClass);
62-
Parameter[] p = null;
63-
final Parameters params = paramsClass.getAnnotation(Parameters.class);
64-
if (params != null) {
65-
p = params.value();
66-
} else {
67-
p = new Parameter[] {paramsClass.getAnnotation(Parameter.class)};
68-
}
69-
final int paramCount = functionalType.getTypeParameters().length;
70-
// TODO: Consider allowing partial override of class @Parameters.
71-
if (p.length == paramCount) {
72-
for (int i=0; i<p.length; i++) {
73-
String key = p[i].key();
74-
final Type itemType = Types.param(Types.parameterizeRaw(type), functionalType, i);
75-
final Class<?> rawItemType = Types.raw(itemType);
76-
final boolean valid = checkValidity(p[i], key, rawItemType, false,
77-
names, problems);
78-
if (!valid) continue; // NB: Skip invalid parameters.
79-
80-
// add item to the list
81-
// TODO make more DRY
82-
try {
83-
final ParameterMember<?> item = //
84-
new FunctionalParameterMember<>(itemType, p[i]);
85-
names.add(key);
86-
items.add(item);
87-
}
88-
catch (final ValidityException exc) {
89-
problems.addAll(exc.problems());
90-
}
91-
}
92-
}
93-
else {
94-
problems.add(new ValidityProblem("Need " + paramCount +
95-
" parameters for " + functionalType.getName() + " but got " +
96-
p.length));
97-
}
66+
parseFunctionalParameters(items, names, problems, findParametersDeclaration(type), type);
9867
}
9968

10069
// Parse field level @Parameter annotations.
70+
parseFieldParameters(items, names, problems, type);
10171

102-
final List<Field> fields = ClassUtils.getAnnotatedFields(type,
103-
Parameter.class);
104-
105-
for (final Field f : fields) {
106-
f.setAccessible(true); // expose private fields
72+
// Fail if there were any problems.
73+
if (!problems.isEmpty()) throw new ValidityException(problems);
10774

108-
final Parameter param = f.getAnnotation(Parameter.class);
75+
return items;
76+
}
77+
78+
public static List<Member<?>> parse(final Class<?> c, final Field field) throws ValidityException {
79+
if (c == null || field == null) return null;
10980

110-
final String name = f.getName();
111-
final boolean isFinal = Modifier.isFinal(f.getModifiers());
112-
final boolean valid = checkValidity(param, name, f.getType(),
113-
isFinal, names, problems);
114-
if (!valid) continue; // NB: Skip invalid parameters.
81+
field.setAccessible(true);
82+
83+
final ArrayList<Member<?>> items = new ArrayList<>();
84+
final ArrayList<ValidityProblem> problems = new ArrayList<>();
85+
final Set<String> names = new HashSet<>();
86+
final Type fieldType = Types.fieldType(field, c);
11587

116-
// add item to the list
117-
try {
118-
final ParameterMember<?> item = new FieldParameterMember<>(f, type);
119-
names.add(name);
120-
items.add(item);
121-
}
122-
catch (final ValidityException exc) {
123-
problems.addAll(exc.problems());
124-
}
125-
}
88+
checkModifiers(field.toString() + ": ", problems, field.getModifiers(), false, Modifier.STATIC, Modifier.FINAL);
89+
parseFunctionalParameters(items, names, problems, field, fieldType);
12690

12791
// Fail if there were any problems.
128-
129-
if (!problems.isEmpty()) throw new ValidityException(problems);
92+
if (!problems.isEmpty()) {
93+
throw new ValidityException(problems);
94+
}
13095

13196
return items;
13297
}
@@ -140,12 +105,104 @@ public static <T> Field field(final Member<T> item) {
140105
}
141106

142107
// -- Helper methods --
108+
109+
/**
110+
* Helper to check for several modifiers at once.
111+
*
112+
* @param message
113+
* @param problems
114+
* @param actualModifiers
115+
* @param requiredModifiers
116+
*/
117+
private static void checkModifiers(String message, final ArrayList<ValidityProblem> problems,
118+
final int actualModifiers, final boolean negate, final int... requiredModifiers) {
119+
for (int mod : requiredModifiers) {
120+
if (negate) {
121+
if ((actualModifiers & mod) != 0) {
122+
problems.add(
123+
new ValidityProblem(message + "Illegal modifier. Must not be " + Modifier.toString(mod)));
124+
}
125+
} else {
126+
if ((actualModifiers & mod) == 0) {
127+
problems.add(new ValidityProblem(message + "Illegal modifier. Must be " + Modifier.toString(mod)));
128+
}
129+
}
130+
}
131+
}
132+
133+
private static void parseFieldParameters (final ArrayList<Member<?>> items, final Set<String> names, final ArrayList<ValidityProblem> problems,
134+
Class<?> annotatedClass) {
135+
final List<Field> fields = ClassUtils.getAnnotatedFields(annotatedClass,
136+
Parameter.class);
137+
138+
for (final Field f : fields) {
139+
f.setAccessible(true); // expose private fields
140+
141+
final Parameter param = f.getAnnotation(Parameter.class);
142+
143+
final String name = f.getName();
144+
final boolean isFinal = Modifier.isFinal(f.getModifiers());
145+
final boolean valid = checkValidity(param, name, f.getType(),
146+
isFinal, names, problems);
147+
if (!valid) continue; // NB: Skip invalid parameters.
148+
149+
// add item to the list
150+
try {
151+
final ParameterMember<?> item = new FieldParameterMember<>(f, annotatedClass);
152+
names.add(name);
153+
items.add(item);
154+
}
155+
catch (final ValidityException exc) {
156+
problems.addAll(exc.problems());
157+
}
158+
}
159+
}
160+
161+
private static void parseFunctionalParameters(final ArrayList<Member<?>> items, final Set<String> names, final ArrayList<ValidityProblem> problems,
162+
AnnotatedElement annotationBearer, Type type) {
163+
Parameter[] annotations = parameters(annotationBearer);
164+
165+
166+
final Class<?> functionalType = findFunctionalInterface(Types.raw(type), annotations.length);
167+
if (functionalType == null) {
168+
problems.add(new ValidityProblem("Could not find functional interface of " + type.getTypeName() + " with the the required number of "
169+
+ "parameters: " + annotations.length));
170+
}
171+
172+
// TODO: Consider allowing partial override of class @Parameters.
173+
for (int i=0; i<annotations.length; i++) {
174+
String key = annotations[i].key();
175+
176+
Type paramType = type;
177+
if (type instanceof Class) {
178+
paramType = Types.parameterizeRaw((Class<?>) type);
179+
}
180+
181+
final Type itemType = Types.param(paramType, functionalType, i);
182+
final Class<?> rawItemType = Types.raw(itemType);
183+
final boolean valid = checkValidity(annotations[i], key, rawItemType, false,
184+
names, problems);
185+
if (!valid) continue; // NB: Skip invalid parameters.
186+
187+
// add item to the list
188+
try {
189+
final ParameterMember<?> item = //
190+
new FunctionalParameterMember<>(itemType, annotations[i]);
191+
names.add(key);
192+
items.add(item);
193+
}
194+
catch (final ValidityException exc) {
195+
problems.addAll(exc.problems());
196+
}
197+
}
198+
199+
}
143200

144201
private static boolean isImmutable(final Class<?> type) {
145202
// NB: All eight primitive types, as well as the boxed primitive
146203
// wrapper classes, as well as strings, are immutable objects.
147-
return ClassUtils.isNumber(type) || ClassUtils.isText(type) || //
148-
ClassUtils.isBoolean(type);
204+
return Types.isNumber(type) || Types.isText(type) || //
205+
Types.isBoolean(type);
149206
}
150207

151208
/**
@@ -167,7 +224,15 @@ private static Class<?> findParametersDeclaration(final Class<?> type) {
167224
return null;
168225
}
169226

170-
private static Class<?> findFunctionalInterface(Class<?> type) {
227+
/**
228+
* Searches for a {@code @FunctionalInterface} annotated interface in the
229+
* class hierarchy of the specified type. The first one that is found will
230+
* be returned. If no such interface can be found, null will be returned.
231+
*
232+
* @param type
233+
* @return
234+
*/
235+
public static Class<?> findFunctionalInterface(Class<?> type) {
171236
if (type == null) return null;
172237
if (type.getAnnotation(FunctionalInterface.class) != null) return type;
173238
for (Class<?> iface : type.getInterfaces()) {
@@ -176,8 +241,34 @@ private static Class<?> findFunctionalInterface(Class<?> type) {
176241
}
177242
return findFunctionalInterface(type.getSuperclass());
178243
}
244+
245+
/**
246+
* Searches for a {@code @FunctionalInterface} annotated interface in the
247+
* class hierarchy of the specified type with the specified number of
248+
* type parameters. After the first interface is found, its super interfaces
249+
* will be checked. If no such interface can be found, null will be returned.
250+
*
251+
* @param type
252+
* @param numberOfParams
253+
* @return
254+
*/
255+
public static Class<?> findFunctionalInterface(Class<?> type, int numberOfParams) {
256+
Class<?> i = findFunctionalInterface(type);
257+
if (i == null) {
258+
return null;
259+
}
260+
if (i != null && i.getTypeParameters().length == numberOfParams) {
261+
return i;
262+
} else {
263+
for (Class<?> iface : i.getInterfaces()) {
264+
final Class<?> result = findFunctionalInterface(iface, numberOfParams);
265+
if (result != null) return result;
266+
}
267+
}
268+
return null;
269+
}
179270

180-
private static boolean checkValidity(Parameter param, String name,
271+
public static boolean checkValidity(Parameter param, String name,
181272
Class<?> type, boolean isFinal, Set<String> names,
182273
ArrayList<ValidityProblem> problems)
183274
{
@@ -209,4 +300,15 @@ private static boolean checkValidity(Parameter param, String name,
209300

210301
return valid;
211302
}
303+
304+
305+
306+
public static Parameter[] parameters(final AnnotatedElement element) {
307+
final Parameters params = element.getAnnotation(Parameters.class);
308+
if (params != null) {
309+
return params.value();
310+
}
311+
final Parameter p = element.getAnnotation(Parameter.class);
312+
return p == null ? new Parameter[0] : new Parameter[] { p };
313+
}
212314
}

0 commit comments

Comments
 (0)