FieldReference.java

package net.morimekta.terminal.args.reference;

import net.morimekta.terminal.args.ArgException;

import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Type;

public class FieldReference implements Reference {
    final Object           instance;
    final Field            field;
    final AccessibleObject annotationRef;

    public FieldReference(
            Object instance,
            Field field,
            AccessibleObject annotationRef) {
        this.instance = instance;
        this.field = field;
        this.annotationRef = annotationRef;
    }

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

    @Override
    public String getUsage() {
        return "Set " + getName() + ".";
    }

    @Override
    public Object get() {
        try {
            return field.get(instance);
        } catch (IllegalAccessException e) {
            throw new ArgException(e.getMessage(), e);
        }
    }

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

    @Override
    public <A extends Annotation> A getAnnotation(Class<A> annotation) {
        return annotationRef.getAnnotation(annotation);
    }

    public Class<?> getType() {
        return field.getType();
    }

    public Type getGenericType() {
        return field.getGenericType();
    }
}