当函数式接口作为参数传入时,有时要获取传入的函数式接口的名称,可以利用SerializedLambda来获取
@FunctionalInterface
public interface MyFunction<T,R> extends Function<T,R>, Serializable {
default SerializedLambda getSerializedLambda() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method method = getClass().getDeclaredMethod("writeReplace");
boolean bAccess = method.isAccessible();
method.setAccessible(true);
SerializedLambda serializedLambda = (SerializedLambda) method.invoke(this);
method.setAccessible(true);
return serializedLambda;
}
default String getMethodName() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
SerializedLambda serializedLambda = getSerializedLambda();
String methodName = serializedLambda.getImplMethodName();
String className = serializedLambda.getImplClass();
return methodName;
}
}
public class Test{
String testMethed(){
return "test"
}
void mian(){
}
static <T> void getMethedName(MyFunction<Test,String> function) {
String methedName = function.getMethodName();
}
}
|