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

org.algorithmx.rules.bind.BindingDeclaration Maven / Gradle / Ivy

There is a newer version: 0.79.50
Show newest version
/**
 * This software is licensed under the Apache 2 license, quoted below.
 *
 * Copyright (c) 2019, algorithmx.org ([email protected])
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.algorithmx.rules.bind;

import org.algorithmx.rules.core.UnrulyException;
import org.algorithmx.rules.util.LambdaUtils;
import org.algorithmx.rules.util.ReflectionUtils;

import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.function.Function;

/**
 * Convenient Function to create Bindings in the form of name -> value.
 *
 * For Example : name -> String, value -> Integer, salary -> java.util.BigDecimal.
 *
 * @author Max Arulananthan
 * @since 1.0
 */
@FunctionalInterface
public interface BindingDeclaration extends Function, Serializable {

    long serialVersionUID = -0L;

    /**
     * Retrieves the name of the Binding from the Function (Lambda).
     *
     * @return name of the Binding.
     */
    default String name() {
        // Serialize the Lambda to be able to retrieve the details of the Lambda.
        SerializedLambda lambda = LambdaUtils.getSafeSerializedLambda(this);

        // It's not a Lambda
        if (lambda == null) {
            throw new UnrulyException("BindingDeclaration can only be used as a Lambda expression");
        }

        // Find the class
        Class implementationClass = LambdaUtils.getImplementationClass(lambda);
        // Find the method
        Method implementationMethod = LambdaUtils.getImplementationMethod(lambda, implementationClass);
        // Get the parameter names. In this ase there will be a single parameter.
        String[] parameterNames = ReflectionUtils.getParameterNames(implementationMethod);
        // Extract the name
        return parameterNames[0];
    }

    /**
     * Retrieves the type of the Binding from the Function (Lambda).
     *
     * @return type (class) of the Binding.
     */
    default Object value() {
        return apply(name());
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy