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

com.es.plus.adapter.tools.LambdaUtils Maven / Gradle / Ivy

There is a newer version: 0.3.941
Show newest version
/*
 *  from organization baomidou
 *
 * 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 com.es.plus.adapter.tools;


import com.es.plus.adapter.exception.EsException;

import java.lang.ref.WeakReference;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

public final class LambdaUtils {

    private static final Map> FUNC_CACHE = new ConcurrentHashMap<>();

    public static  SerializedLambda resolve(SFunction func) {
        Class clazz = func.getClass();
        String name = clazz.getName();
        return Optional.ofNullable(FUNC_CACHE.get(name))
                .map(WeakReference::get)
                .orElseGet(() -> {
                    SerializedLambda lambda = SerializedLambda.resolve(func);
                    FUNC_CACHE.put(name, new WeakReference<>(lambda));
                    return lambda;
                });
    }

    public static  String getFieldName(SFunction func) {
        SerializedLambda serializedLambda = resolve(func);
        return getName(serializedLambda);
    }

    private static String getName(SerializedLambda lambda) {
        return methodToProperty(lambda.getImplMethodName());
    }

    private static String methodToProperty(String name) {
        if (name.startsWith("is")) {
            name = name.substring(2);
        } else if (name.startsWith("get") || name.startsWith("set")) {
            name = name.substring(3);
        } else {
            throw new EsException("Error parsing property name '" + name + "'.  Didn't start with 'is', 'get' or 'set'.");
        }

        if (name.length() == 1 || (name.length() > 1 && !Character.isUpperCase(name.charAt(1)))) {
            name = name.substring(0, 1).toLowerCase(Locale.ENGLISH) + name.substring(1);
        }

        return name;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy