Refactor ReflectionExtractor to use composable extractors (NullSafe and UnwrapOptional)
@@ -30,7 +30,7 @@ class ReflectionExtractor implements PathExtractor {
private final MemberExtractor extractor;
ReflectionExtractor() {
- this.extractor = MemberExtractor.ofReflection();
+ this.extractor = new UnwrapOptional(new NullSafe(MemberExtractor.ofReflection()));
}
@Override
@@ -41,8 +41,7 @@ class ReflectionExtractor implements PathExtractor {
Object result = instance;
for (AnnotatedElement member: path.paths()) {
- result = extract((Member) member, result);
- result = maybeUnwrapOptional(result);
+ result = extractor.extract((Member) member, result);
if (result == null) {
return null;
}
@@ -51,16 +50,31 @@ class ReflectionExtractor implements PathExtractor {
return result;
}
- private Object extract(Member member, Object instance) {
- if (instance == null) {
- return null;
+ private static class NullSafe implements MemberExtractor {
+ private final MemberExtractor delegate;
+
+ private NullSafe(MemberExtractor delegate) {
+ this.delegate = delegate;
+ }
+
+ @Override
+ public Object extract(Member member, Object instance) {
+ return instance != null ? delegate.extract(member, instance) : null;
+ }
}
- return extractor.extract(member, instance);
+ private static class UnwrapOptional implements MemberExtractor {
+
+ private final MemberExtractor delegate;
+
+ private UnwrapOptional(MemberExtractor delegate) {
+ this.delegate = delegate;
}
@SuppressWarnings("unchecked")
- private static Object maybeUnwrapOptional(Object maybeOptional) {
+ @Override
+ public Object extract(Member member, Object instance) {
+ Object maybeOptional = delegate.extract(member, instance);
if ((maybeOptional instanceof Optional)) {
return ((Optional) maybeOptional).orElse(null);
}
@@ -68,7 +82,8 @@ class ReflectionExtractor implements PathExtractor {
if (maybeOptional instanceof com.google.common.base.Optional) {
return ((com.google.common.base.Optional) maybeOptional).orNull();
}
-
return maybeOptional;
}
}
+
+}
