Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
package io.github.joselion.springr2dbcrelationships.helpers;
import static java.lang.invoke.LambdaMetafactory.metafactory;
import static java.lang.invoke.MethodType.methodType;
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import org.eclipse.jdt.annotation.Nullable;
import io.github.joselion.maybe.Maybe;
import io.github.joselion.springr2dbcrelationships.exceptions.ReflectException;
/**
* Reflection helpers.
*/
public final class Reflect {
private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
private Reflect() {
throw new UnsupportedOperationException("Reflect is a helper class");
}
/**
* Finds and invokes the getter of a field in the provided target.
*
* @param the return type of the getter
* @param target the target instance were the getter is invoked
* @param field the field to invoke the getter
* @return the result of invoking the getter
* @throws ReflectException if the getter method cannot be found or fails to
* be invoked
*/
@Nullable
public static T getter(final Object target, final Field field) {
final var targetType = field.getDeclaringClass();
final var fieldType = field.getType();
final var getterMethod = Reflect.findGetterMethod(field);
final var getterFn = Maybe
.from(() -> metafactory(
LOOKUP,
"apply",
methodType(Function.class),
methodType(Object.class, Object.class),
getterMethod,
methodType(fieldType, targetType)
))
.map(CallSite::getTarget)
.solve(method -> method.invoke()) // NOSONAR
.solve(Commons::>cast)
.orThrow(ReflectException::of);
return getterFn.apply(target);
}
/**
* Curried version of {@link Reflect#getter(Object, Field)} overload.
*
* @param the return type of the getter
* @param field the field to invoke the getter
* @return a function that takes the target as parameter and returns the
* result of invoking the getter of the field
*/
public static Function