Last active
August 29, 2015 14:03
-
-
Save thomasdarimont/e9d02080f0b7ab8307af to your computer and use it in GitHub Desktop.
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
Hello | |
intercept call to: public abstract java.lang.String de.tutorials.training.ReflectiveDefaultMethodCallExample$Hello.greet(java.lang.String) | |
Hello bubu |
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
package de.tutorials.training; | |
import org.springframework.core.env.SystemEnvironmentPropertySource; | |
import java.lang.invoke.MethodHandles; | |
import java.lang.reflect.Method; | |
import java.lang.reflect.Proxy; | |
/** | |
* [USER=136855]@author[/USER] Thomas Darimont | |
*/ | |
public class ReflectiveDefaultMethodCallExample { | |
static interface Hello { | |
String greet(String arg); | |
default String hello(String arg) { | |
System.out.println("Hello"); | |
return greet(arg); | |
} | |
} | |
public static void main(String[] args) throws Throwable{ | |
final Hello target = new Hello(){ | |
@Override | |
public String greet(String arg) { | |
return "Hello " + arg; | |
} | |
}; | |
Hello hello = | |
(Hello)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class[]{Hello.class}, | |
(Object proxy, Method method, Object[] arguments) -> { | |
System.out.println("intercept call to: " + method); | |
return method.invoke(target,arguments); | |
}); | |
Method method = Hello.class.getMethod("hello", String.class); | |
Object result = MethodHandles.lookup() | |
.in(method.getDeclaringClass()) | |
.unreflectSpecial(method,method.getDeclaringClass()) | |
.bindTo(hello) | |
.invokeWithArguments("bubu"); | |
System.out.println(result); //Hello bubu | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment