Skip to content

Method: PersistentPropertyMatcher(Class)

1: package cz.cvut.kbss.jopa.model.metamodel.gen;
2:
3: import cz.cvut.kbss.jopa.utils.EntityPropertiesUtils;
4: import net.bytebuddy.description.method.MethodDescription;
5: import net.bytebuddy.matcher.ElementMatcher;
6:
7: import java.lang.reflect.Field;
8: import java.util.Objects;
9: import java.util.Optional;
10:
11: /**
12: * Matches only persistent attribute getters/setters.
13: * <p>
14: * This matcher checks that there exists a persistent field corresponding to the method name that appears to be a
15: * getter/setter.
16: *
17: * @param <T> MethodDescription
18: */
19: public abstract class PersistentPropertyMatcher<T extends MethodDescription> extends ElementMatcher.Junction.ForNonNullValues<T> {
20:
21: private final Class<?> parentType;
22:
23: public PersistentPropertyMatcher(Class<?> parentType) {this.parentType = Objects.requireNonNull(parentType);}
24:
25: @Override
26: protected boolean doMatch(T target) {
27: final String name = target.getName();
28: final Optional<String> fieldName = resolveFieldName(name, target);
29: return fieldName.flatMap(this::tryFindingField).map(f -> !EntityPropertiesUtils.isFieldTransient(f))
30: .orElse(false);
31: }
32:
33: protected abstract Optional<String> resolveFieldName(String methodName, MethodDescription methodDesc);
34:
35: protected Optional<Field> tryFindingField(String fieldName) {
36: Class<?> type = parentType;
37: do {
38: try {
39: Field f = type.getDeclaredField(fieldName);
40: return Optional.of(f);
41: } catch (NoSuchFieldException e) {
42: type = type.getSuperclass();
43: }
44: } while (type != null);
45: return Optional.empty();
46: }
47: }