The Java standard library provides a dynamic proxy function that allows an instance of an interface to be dynamically created at runtime. However, what is the dynamic proxy?

What is dynamic Proxy?

As you see above, the dynamic proxy is realized during the runtime. It corresponds to static.

First, let’s see how to write a static Java code as the following.

Defining the interface:

interface Hello {
    void greeting(String name);
}

Then, we need to write the implementation class:

public class SayHello implements Hello {
    public void greeting(String name) {
        System.out.println("Hello, " + name);
    }
}

Create an instance, transform it into an interface, and call:

Hello hello = new SayHello();
hello.greeting("John");

This way is the way we usually write code.

When comes to the dynamic proxy coding, the process as following.

Frist, we still define the interface Hello, but instead of writing the implementation class, we use Proxy.newProxyInstance() to create an object of Hellointerface directly from the one provided API by the JDK . 

This way is not implementing the class but dynamically creating an object of the interface at runtime, which is called dynamic code. The method provided by the JDK for dynamically creating interface objects is called a dynamic proxy.

For example, a simple implementation of a dynamic proxy is as follows:

public class Main {
    public static void main(String[] args)  {

        //call the methods of interface
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println(method);
                if (method.getName().equals("greeting")) {
                    System.out.println("Hello, " + args[0]);
                }
                return null;
            }
        };

        Hello hello = (Hello) Proxy.newProxyInstance(
                Hello.class.getClassLoader(),
                new Class[] {Hello.class},
                handler);
        hello.greeting("Etbye.com readers");
    }
}

interface Hello {
    void greeting(String name);
}

How to create an instance of an interface at runtime?

 The steps of dynamically create an instance at runtime:

  1. Define an InvocationHandlerinstance that is responsible for implementing the method calls of the interface;
  2. By Proxy.newProxyInstance()creating an instance of interface, it requires three parameters:
    • ClassLoader, usually the interface class ClassLoader;
    • An array of interfaces to be implemented, at least one interface needs to be passed in;
    • An InvocationHandlerinstance used to handle interface method calls.
  3. Cast the returned Object to an interface type.