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

gu.sql2java.guava.DeepCacheBuilder Maven / Gradle / Ivy

The newest version!
package gu.sql2java.guava;

import com.google.common.base.Equivalence;
import com.google.common.base.Throwables;
import com.google.common.cache.CacheBuilder;

import static gu.sql2java.guava.DeepEquivalence.DEEP_EQUIVALENCE;

import java.lang.reflect.Method;

public class DeepCacheBuilder {
	/**
	 * 反射调用
	 * {@link CacheBuilder#keyEquivalence(Equivalence)}和{@link CacheBuilder#valueEquivalence(Equivalence)}方法
	 * 
	 * @param builder
	 * @param methodName
	 * @param equivalence
	 * @return always builder
	 */
	@SuppressWarnings("unchecked")
	private static CacheBuilder setBuilderDeepEquivalence(CacheBuilder builder,
			String methodName, Equivalence equivalence) {
		if (builder != null && equivalence != null) {
			// 等价于 builder.keyEquivalence(DEEP_EQUIVALENCE);
			try {
				Method method = CacheBuilder.class.getDeclaredMethod(methodName, Equivalence.class);
				method.setAccessible(true);
				return (CacheBuilder) method.invoke(builder, equivalence);
			} catch (Exception e) {
				Throwables.throwIfUnchecked(e);
				throw new RuntimeException(e);
			}
		}
		return builder;
	}
	/**
	 * 为{@link CacheBuilder}实例指定KEY执行深度比较
	 * @param builder
	 * @return always builder
	 * @since 3.32.0
	 */
	public static final CacheBuilder keyDeepEqual(CacheBuilder builder){
		// 等价于 builder.keyEquivalence(DEEP_EQUIVALENCE);
		return setBuilderDeepEquivalence(builder,"keyEquivalence", DEEP_EQUIVALENCE);
	}
	/**
	 * 为{@link CacheBuilder}实例指定VALUE执行深度比较
	 * @param builder
	 * @return always builder
	 * @since 3.32.0
	 */
	public static final CacheBuilder valueDeepEqual(CacheBuilder builder){
		// 等价于 builder.valueEquivalence(DEEP_EQUIVALENCE);
		return setBuilderDeepEquivalence(builder,"valueEquivalence", DEEP_EQUIVALENCE);
	}
	public static final CacheBuilder newBuilder(){
		return newBuilder(DEEP_EQUIVALENCE,DEEP_EQUIVALENCE);
	}
	public static final CacheBuilder newBuilder(
			Equivalence keyEquivalence,
			Equivalence valueEquivalence){
		CacheBuilder builder = CacheBuilder.newBuilder();
		if(keyEquivalence != null){
			// 等价于 builder.keyEquivalence(keyEquivalence);
			setBuilderDeepEquivalence(builder,"keyEquivalence", keyEquivalence);
		}
		if(valueEquivalence != null){
			// 等价于 builder.valueEquivalence(valueEquivalence);
			setBuilderDeepEquivalence(builder,"valueEquivalence", valueEquivalence);
		}
		return builder;
	}
}