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

se.fortnox.reactivewizard.util.FieldGetter Maven / Gradle / Ivy

There is a newer version: 24.6.0
Show newest version
package se.fortnox.reactivewizard.util;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.function.Function;

/**
 * Represents a getter field.
 */
public class FieldGetter implements Getter {
    private final Function fieldLambda;

    public static  Getter create(Class cls, Field field) {
        AccessorUtil.MemberTypeInfo memberTypeInfo = AccessorUtil.fieldTypeInfo(cls, field);
        return new FieldGetter<>(field, memberTypeInfo.getReturnType(), memberTypeInfo.getGenericReturnType());
    }

    private final Class returnType;
    private final Type     genericReturnType;

    private FieldGetter(Field field, Class returnType, Type genericReturnType) {
        this.returnType = returnType;
        this.genericReturnType = genericReturnType;
        field.setAccessible(true);
        this.fieldLambda = instance -> {
            try {
                return (T)field.get(instance);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        };
    }

    @Override
    public T invoke(I instance) {
        return fieldLambda.apply(instance);
    }

    @Override
    public Class getReturnType() {
        return returnType;
    }

    @Override
    public Type getGenericReturnType() {
        return genericReturnType;
    }

    @Override
    public Function getterFunction() {
        return fieldLambda;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy