Skip to content

Instantly share code, notes, and snippets.

@thomasdarimont
Last active August 29, 2015 14:03
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 thomasdarimont/e9d02080f0b7ab8307af to your computer and use it in GitHub Desktop.
Save thomasdarimont/e9d02080f0b7ab8307af to your computer and use it in GitHub Desktop.
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