Created
April 10, 2019 07:49
-
-
Save hpeng526/01c75e904305e98b4920603a85759527 to your computer and use it in GitHub Desktop.
SerializedLambda example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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