com.btc.redg.jpa.ReflectionUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of redg-jpa-providers Show documentation
Show all versions of redg-jpa-providers Show documentation
Name and data type providers for RedG that extract the data from a JPA metamodel.
/*
* Copyright 2017 BTC Business Technology AG
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.btc.redg.jpa;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class ReflectionUtil {
public static List findFields(Class> clazz, Predicate predicate) {
List matchingFields = new ArrayList<>();
Class> c = clazz;
while (c != null) {
for (Field field : c.getDeclaredFields()) {
if (predicate.test(field)) {
matchingFields.add(field);
}
}
c = c.getSuperclass();
}
return matchingFields;
}
public static List findMethods(Class> clazz, Predicate predicate) {
List matchingFields = new ArrayList<>();
Class> c = clazz;
while (c != null) {
for (Method method : c.getDeclaredMethods()) {
if (predicate.test(method)) {
matchingFields.add(method);
}
}
c = c.getSuperclass();
}
return matchingFields;
}
public static List findFieldsByAnnotation(Class> clazz, Class extends Annotation> annotationClass) {
return findFields(clazz, field -> field.isAnnotationPresent(annotationClass));
}
public static List findMethodsByAnnotation(Class> clazz, Class extends Annotation> annotationClass) {
return findMethods(clazz, method -> method.isAnnotationPresent(annotationClass));
}
public static List extends AnnotatedElement> findMembersByAnnotation(Class> clazz, Class extends Annotation> annotationClass) {
List result = new ArrayList<>();
result.addAll(findFields(clazz, field -> field.isAnnotationPresent(annotationClass)));
result.addAll(findMethods(clazz, method -> method.isAnnotationPresent(annotationClass)));
return result;
}
}