Skip to content

Commit 94f3250

Browse files
committed
Made registration more modular
1 parent 41c2e5f commit 94f3250

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed

src/main/java/org/javawebstack/validator/Validator.java

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ public class Validator {
2020
private static final Map<String, Constructor<? extends ValidationRule>> validationRules = new HashMap<>();
2121
private static final Map<Class<?>, Validator> validators = new HashMap<>();
2222

23-
private static final List<Class<? extends Annotation>> ruleAnnotationClasses = new ArrayList<>();
23+
private static final Map<Class<? extends ValidationRule>, Class<? extends Annotation>> ruleAnnotationClasses = new HashMap<>();
2424

2525
static {
2626
registerRuleType("string", StringRule.Validator.class, StringRule.class);
@@ -47,8 +47,8 @@ public class Validator {
4747
}
4848

4949
public static void registerRuleType(String name, Class<? extends ValidationRule> type, Class<? extends Annotation> annotationClass) {
50-
if (!ruleAnnotationClasses.contains(annotationClass))
51-
ruleAnnotationClasses.add(annotationClass);
50+
if (!ruleAnnotationClasses.containsKey(type))
51+
ruleAnnotationClasses.put(type, annotationClass);
5252
try {
5353
Constructor<? extends ValidationRule> constructor = type.getDeclaredConstructor(String[].class);
5454
constructor.setAccessible(true);
@@ -358,20 +358,19 @@ private static Map<String[], ValidationConfig> getClassRules(Field field, Class<
358358
if (r.size() > 0)
359359
addMapRules(f, rules, new String[]{name}, r);
360360
}
361-
for (Class<? extends Annotation> annotation : ruleAnnotationClasses) {
362-
Annotation a = f.getDeclaredAnnotation(annotation);
361+
ruleAnnotationClasses.entrySet().stream().distinct().forEach(annotation -> {
362+
Annotation a = f.getDeclaredAnnotation(annotation.getValue());
363363
if (a != null) {
364364
List<ValidationRule> r = new ArrayList<>();
365365
try {
366-
Class<?> validatorClazz = Class.forName(annotation.getName() + "$Validator"); // stupid way of doing this;
367-
Constructor<ValidationRule> constructor = (Constructor<ValidationRule>) validatorClazz.getDeclaredConstructor(annotation);
366+
Constructor<ValidationRule> constructor = (Constructor<ValidationRule>) annotation.getKey().getDeclaredConstructor(annotation.getValue());
368367
constructor.setAccessible(true);
369368
r.add(constructor.newInstance(a));
370-
} catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException ignored) {}
369+
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException ignored) {}
371370
if (r.size() > 0)
372371
addMapRules(f, rules, new String[]{name}, r);
373372
}
374-
}
373+
});
375374
}
376375
return rules;
377376
}

0 commit comments

Comments
 (0)