Skip to content

Instantly share code, notes, and snippets.

@hpeng526
Created April 10, 2019 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hpeng526/01c75e904305e98b4920603a85759527 to your computer and use it in GitHub Desktop.
Save hpeng526/01c75e904305e98b4920603a85759527 to your computer and use it in GitHub Desktop.
SerializedLambda example
public class TestA {
@Greet(value = false)
public static void functionA() {
System.out.println("hello world");
}
public void functionB(HandlerFunction function) throws Exception {
SerializedLambda serializedLambda = function.serialized();
System.out.println(serializedLambda.getImplMethodName());
System.out.println(serializedLambda.getImplClass());
//要如何在这里拿到传入的 function 的注解呢?
System.out.println(Class.forName(serializedLambda.getCapturingClass())
.getDeclaredMethod(serializedLambda.getImplMethodName()).getAnnotation(Greet.class).value());
function.callback();
// 回调传入的 function
}
public static void main(String[] args) throws Exception {
TestA t = new TestA();
t.functionB((HandlerFunction & Serializable) TestA::functionA);
}
}
@FunctionalInterface
public interface HandlerFunction extends Serializable {
void callback();
default SerializedLambda serialized() {
try {
Method replaceMethod = getClass().getDeclaredMethod("writeReplace");
replaceMethod.setAccessible(true);
return (SerializedLambda) replaceMethod.invoke(this);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment