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

io.yawp.repository.shields.ShieldInfo Maven / Gradle / Ivy

There is a newer version: 2.08alpha
Show newest version
package io.yawp.repository.shields;

import io.yawp.repository.actions.ActionKey;
import io.yawp.repository.actions.ActionMethod;
import io.yawp.repository.actions.InvalidActionMethodException;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShieldInfo {

    private Class> shieldClazz;

    private Map actionMethods;

    private transient Constructor> constructor;

    public ShieldInfo(Class> shieldClazz) {
        this.shieldClazz = shieldClazz;
        this.constructor = cacheConstructor(shieldClazz);
        parseActionMethods();
    }

    public Class> getShieldClazz() {
        return shieldClazz;
    }

    public Map getActionMethods() {
        return actionMethods;
    }

    private void parseActionMethods() {
        this.actionMethods = new HashMap();

        Method[] methods = shieldClazz.getDeclaredMethods();
        for (Method method : methods) {
            if (!ActionMethod.isAction(method)) {
                continue;
            }

            List actionKeys = getActionKeysFor(method);

            for (ActionKey actionKey : actionKeys) {
                actionMethods.put(actionKey, method);
            }
        }
    }

    private List getActionKeysFor(Method method) {
        try {
            return ActionMethod.getActionKeysFor(method);
        } catch (InvalidActionMethodException e) {
            throw new RuntimeException("Invalid action method in shield: " + shieldClazz.getName() + "." + method.getName(), e);
        }
    }

    private Constructor> cacheConstructor(Class> shieldClazz) {
        try {
            Constructor> constructor = shieldClazz.getConstructor();
            constructor.setAccessible(true);
            return constructor;
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    public Shield newInstance() {
        try {
            return constructor.newInstance();
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy