Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Hello
intercept call to: public abstract java.lang.String de.tutorials.training.ReflectiveDefaultMethodCallExample$Hello.greet(java.lang.String)
Hello bubu
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
You can’t perform that action at this time.