All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.btc.redg.jpa.ReflectionUtil Maven / Gradle / Ivy

Go to download

Name and data type providers for RedG that extract the data from a JPA metamodel.

There is a newer version: 2.4.1
Show newest version
/*
 * 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 annotationClass) {
		return findFields(clazz, field -> field.isAnnotationPresent(annotationClass));
	}

	public static List findMethodsByAnnotation(Class clazz, Class annotationClass) {
		return findMethods(clazz, method -> method.isAnnotationPresent(annotationClass));
	}

	public static List findMembersByAnnotation(Class clazz, Class annotationClass) {
		List result = new ArrayList<>();
		result.addAll(findFields(clazz, field -> field.isAnnotationPresent(annotationClass)));
		result.addAll(findMethods(clazz, method -> method.isAnnotationPresent(annotationClass)));
		return result;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy