Since Java 8 interfaces could have default methods. I know how to invoke the method explicitly from the implementing method, i.e. (see Explicitly calling a default method in Java)
But how do I invoke the default method using reflection for example on a proxy?
Example:
interface IExample {
  String getText();
  default void printInfo(){
    System.out.println(getText());
  }
}
class Example implements IExample {
  public static void main(String... args) throws Exception {
    Example ex = new Example();
    IExample target =
            (IExample) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class[]{IExample.class}, (Object proxy, Method method, Object[] arguments) -> {
                if(method.isDefault()){
                    //how to invoke super here?
                } else {
                    return method.invoke(ex, arguments);
                }
            });
    System.out.println(target.getText());
    target.printInfo();
  }
  @Override
  public String getText() {
    return "myText";
  }
  @Override
  public void printInfo() {
    System.out.println("info");
  }
}
Aucun commentaire:
Enregistrer un commentaire