Skip to content

Instantly share code, notes, and snippets.

@sudot
Created November 28, 2018 11:47
Show Gist options
  • Save sudot/4c824d9fee9d9e3fed1eec1ff523ca3f to your computer and use it in GitHub Desktop.
Save sudot/4c824d9fee9d9e3fed1eec1ff523ca3f to your computer and use it in GitHub Desktop.
LombokReflections
import java.beans.Introspector;
import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.function.Function;
import java.util.regex.Pattern;
/**
* Lombok反射工具
*
* @author tangjialin on 2018-11-27.
*/
public class LombokReflections {
private static final Pattern GET_SET_PATTERN = Pattern.compile("^(g|s)et[A-Z][\\w\\$]*");
private static final Pattern IS_PATTERN = Pattern.compile("^is[A-Z][\\w\\$]*");
private LombokReflections() {
}
/**
* 从Lombok函数中获取方法名称反解字段名称
*
* @param fn Lombok函数
* @param <T> 入参类型
* @param <R> 结果的参数类型
* @return 返回字段名称
*/
public static <T, R> String fnToFieldName(LombokFn<T, R> fn) {
try {
Method method = fn.getClass().getDeclaredMethod("writeReplace");
method.setAccessible(Boolean.TRUE);
SerializedLambda serializedLambda = (SerializedLambda) method.invoke(fn);
String methodName = serializedLambda.getImplMethodName();
if (GET_SET_PATTERN.matcher(methodName).matches()) {
methodName = methodName.substring(3);
} else if (IS_PATTERN.matcher(methodName).matches()) {
methodName = methodName.substring(2);
}
return Introspector.decapitalize(methodName);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
/**
* FunctionalInterface
*
* @author tangjialin on 2018-11-27.
*/
public interface LombokFn<T, R> extends Function<T, R>, Serializable {
}
}
import org.junit.Assert;
import org.junit.Test;
public class LombokReflectionsTest {
@Test
public void fnToFieldName() {
// 这个方法编译不通过,必须要有返回值的
// LombokReflections.fnToFieldName(DemoBean::isnxx);
Assert.assertEquals("nxx", LombokReflections.fnToFieldName(DemoBean::isNxx));
Assert.assertEquals("n_na$", LombokReflections.fnToFieldName(DemoBean::getN_na$));
Assert.assertEquals("name", LombokReflections.fnToFieldName(DemoBean::setName));
Assert.assertEquals("name", LombokReflections.fnToFieldName(DemoBean::name));
Assert.assertEquals("age", LombokReflections.fnToFieldName(DemoBean::Age));
}
public static class DemoBean {
public void isnxx() {
}
public String isNxx() {
return null;
}
public String getN_na$() {
return null;
}
public DemoBean setName() {
return this;
}
public String name() {
return null;
}
public String Age() {
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment