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

host.anzo.commons.utils.ClassUtils Maven / Gradle / Ivy

There is a newer version: 1.29
Show newest version
package host.anzo.commons.utils;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author ANZO
 * @since 12.09.2013
 */
@Slf4j
public class ClassUtils {
    public static Object singletonInstance(Class clazz) {
        try {
            Method method = clazz.getDeclaredMethod("getInstance");
            return method.invoke(null);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
            throw null;
        }
    }

    public static Object singletonInstanceMethod(Class clazz, Method method) {
        try {
            final Object singletonInstance = singletonInstance(clazz);
            if (singletonInstance != null) {
                return method.invoke(singletonInstance);
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
            return null;
        }
    }

    public static @NotNull Collection getMethodsAnnotatedWith(final Class type, final Class annotation) {
        final Map methods = new HashMap<>();
        Class klass = type;
        while (klass != Object.class) {
            final List allMethods = Arrays.stream(klass.getMethods()).filter(method -> method.isAnnotationPresent(annotation)).toList();
            for (Method method : allMethods) {
                if (!methods.containsKey(method.getName())) {
                    methods.put(method.getName(), method);
                }
            }
            klass = klass.getSuperclass();
        }
        return methods.values();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy