How to Explicitly Invoke a Default Method from a Dynamic Proxy in Java?

Question

How can I explicitly invoke a default method from a dynamic proxy in Java?

public interface MyInterface {
    default void defaultMethod() {
        System.out.println("Default Method");
    }
}

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynamicProxyExample {
    public static void main(String[] args) {
        MyInterface proxy = (MyInterface) Proxy.newProxyInstance(
            MyInterface.class.getClassLoader(),
            new Class[] { MyInterface.class },
            new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (method.getName().equals("defaultMethod")) {
                        // Invoke the default method explicitly
                        return MyInterface.super.defaultMethod();
                    }
                    return null;
                }
            });
        proxy.defaultMethod(); // Calls the proxy, which triggers the defaultMethod
    }
}

Answer

In Java, you can use dynamic proxies to create instances of interfaces at runtime. This is particularly useful when you want to add behavior or intercept method calls. However, invoking default methods defined in interfaces through proxies can be tricky. Here, we will explore how to do this correctly and effectively.

public interface MyInterface {
    default void defaultMethod() {
        System.out.println("Default Method");
    }
}

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynamicProxyExample {
    public static void main(String[] args) {
        MyInterface proxy = (MyInterface) Proxy.newProxyInstance(
            MyInterface.class.getClassLoader(),
            new Class[] { MyInterface.class },
            new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (method.getName().equals("defaultMethod")) {
                        // Invoke the default method explicitly
                        return MyInterface.super.defaultMethod();
                    }
                    return null;
                }
            });
        proxy.defaultMethod(); // Calls the proxy, which triggers the defaultMethod
    }
}

Causes

  • Lack of understanding of how dynamic proxies work with interfaces.
  • Confusion on how default methods are treated in terms of proxy invocations.

Solutions

  • Implement handling in the invoke method of the InvocationHandler to check for the default method's name.
  • Use MyInterface.super.defaultMethod() to invoke the default method.

Common Mistakes

Mistake: Not implementing default method invocation properly in the InvocationHandler.

Solution: Ensure you check the method name and call MyInterface.super.defaultMethod() for default methods.

Mistake: Using Instance instead of Interface type for proxy object

Solution: Always cast the proxy object to the interface it implements to avoid ClassCastException.

Helpers

  • Java dynamic proxy
  • invoke default method
  • Java Reflection
  • InvocationHandler
  • default methods in interface

Related Questions

⦿How to Enforce a Non-Null Field in a JSON Object?

Learn how to ensure specific fields in a JSON object are not null using JavaScript and JSON schema validation techniques.

⦿How to De-serialize JSON into a Polymorphic Object Model Using Spring and the @JsonTypeInfo Annotation

Learn how to efficiently deserialize JSON to a polymorphic object model in Spring using the JsonTypeInfo annotation.

⦿Can JPA Be Used with Table Views in Database Applications?

Explore how JPA interacts with table views in databases and learn if its feasible to use them effectively.

⦿How to Use Non-terminal forEach() in a Java Stream?

Learn how to efficiently use the nonterminal forEach method in Java Streams with examples and common pitfalls.

⦿How Can You Implement a Java Virtual Machine (JVM) in Java?

Learn how to implement a Java Virtual Machine JVM using Java with stepbystep guidance and code examples.

⦿How to Create a String Constant in Spring Context XML Files Efficiently?

Discover shorthand methods to define string constants in Spring context XML files improving configuration clarity and efficiency.

⦿How to Declare a Generic Method in Java?

Learn how to effectively declare and use generic methods in Java with examples and common pitfalls.

⦿How to Get Started with Java EE Development: A Beginner's Guide

Discover effective steps to kickstart your Java EE learning journey with this comprehensive guide for beginners.

⦿Why Are Some Tabs Missing in VisualVM?

Discover why VisualVM might not be displaying all tabs and how to fix it. Explore causes solutions and troubleshooting tips.

© Copyright 2025 - CodingTechRoom.com