PutterMethodReference.java

package net.morimekta.terminal.args.reference;

import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Map;

public class PutterMethodReference extends MethodReference implements PutterReference {
    private final Method putter;

    public PutterMethodReference(
            Object instance,
            Method getter,
            Method putter,
            AccessibleObject annotationRef) {
        super(instance, getter, annotationRef);
        this.putter = putter;
    }

    @Override
    public String getName() {
        return putter.getName();
    }

    @Override
    public void put(Object key, Object value) {
        safeInvoke(putter, instance, key, value);
    }

    @Override
    public boolean isAnnotationPresent(Class<? extends Annotation> annotation) {
        return putter.isAnnotationPresent(annotation) || super.isAnnotationPresent(annotation);
    }

    @Override
    public <A extends Annotation> A getAnnotation(Class<A> annotation) {
        if (putter.isAnnotationPresent(annotation)) {
            return putter.getAnnotation(annotation);
        }
        return super.getAnnotation(annotation);
    }

    @Override
    public Class<?> getType() {
        if (getter != null) {
            return getter.getReturnType();
        }
        return Map.class;
    }

    @Override
    public Type getGenericType() {
        if (getter != null) {
            return getter.getGenericReturnType();
        }
        return new ReferenceParameterizedType(getType(), getKeyType(), getValueType());
    }

    @Override
    public Class<?> getKeyType() {
        return putter.getParameters()[0].getType();
    }

    @Override
    public Class<?> getValueType() {
        return putter.getParameters()[1].getType();
    }
}