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

cn.sylinx.hbatis.kit.LambdaUtil Maven / Gradle / Ivy

The newest version!
package cn.sylinx.hbatis.kit;

import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.WeakHashMap;

import cn.sylinx.hbatis.exception.HbatisException;
import cn.sylinx.hbatis.log.GLog;

public class LambdaUtil {

	private static final Map, SerializedLambda> LAMBDA_CACHE = new WeakHashMap<>();

	public static String methodToFieldName(String methodName) {
		return capitalize(methodName.replace("get", ""));
	}

	public static String capitalize(String input) {
		return input.substring(0, 1).toLowerCase() + input.substring(1, input.length());
	}

	public static String getLambdaFieldName(Serializable lambda) {
		SerializedLambda serializedLambda = computeSerializedLambda(lambda);
		if (serializedLambda == null) {
			throw new HbatisException("获取实体列名异常");
		}
		
		return methodToFieldName(serializedLambda.getImplMethodName());
	}

	private static SerializedLambda computeSerializedLambda(Serializable lambda) {

		Class cl = lambda.getClass();
		SerializedLambda cacheLambda = LAMBDA_CACHE.get(cl);
		if (cacheLambda != null) {
			GLog.debug("SerializedLambda bingo, class:{}", cl);
			return cacheLambda;
		}

		try {
			Method m = cl.getDeclaredMethod("writeReplace");
			m.setAccessible(true);
			Object replacement = m.invoke(lambda);
			if (replacement instanceof SerializedLambda) {
				cacheLambda = (SerializedLambda) replacement;
				LAMBDA_CACHE.put(cl, cacheLambda);
			}
		} catch (Exception e) {
			GLog.error("get lambda column name error", e);
			throw new HbatisException("get lambda column name fail", e);
		}

		return cacheLambda;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy