de.thksystems.util.reflection.AnnotationUtils Maven / Gradle / Ivy
/*
* tksCommons
*
* Author : Thomas Kuhlmann (ThK-Systems, http://www.thk-systems.de) License : LGPL (https://www.gnu.org/licenses/lgpl.html)
*/
package de.thksystems.util.reflection;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public final class AnnotationUtils {
private AnnotationUtils() {
}
/**
* Gets the names of all fields annotated with the given annotation.
*/
public static String[] getFieldNamesAnnotatedWith(Object obj, Class extends Annotation> annotationClass) {
Field[] fields = getFieldsAnnotatedWith(obj, annotationClass);
String[] fieldNames = new String[fields.length];
for (int i = 0; i < fields.length; i++) {
fieldNames[i] = fields[i].getName();
}
return fieldNames;
}
/**
* Gets all fields annotated with the given annotation.
*/
public static Field[] getFieldsAnnotatedWith(Object obj, Class extends Annotation> annotationClass) {
List foundFields = new ArrayList<>();
Field[] objFields = obj.getClass().getDeclaredFields();
for (Field objField : objFields) {
if (objField.isAnnotationPresent(annotationClass)) {
foundFields.add(objField);
}
}
return foundFields.toArray(new Field[foundFields.size()]);
}
}