Java Dynamic Proxy without a target?

Weird question...

How can I use the Java Invocation Interceptor, as when using dynamic proxies, without actually having the target?

For example, I would like to create an uber object that can stand on a dozen or so interfaces specified at runtime, without having to use an object that implements any of them.

It basically works as a __call function from most dynamic languages.

Thoughts?

+3
source share
1 answer

Perhaps I do not understand the question (if so, let me know!), But will you start with this?

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

public class Main
{
    public static void main(final String[] argv)
    {
        final Object             object;
        final InvocationHandler  handler;
        final Runnable           runnable;
        final Comparable<Object> comparable;


        handler = new InvocationHandler()
        {
            public Object invoke(final Object   proxy,
                                 final Method   method,
                                 final Object[] args)
                throws Throwable
            {
                System.out.println(proxy.getClass());
                System.out.println(method);
                System.out.println(Arrays.toString(args));
                return (0);
            }
        };

        object = Proxy.newProxyInstance(Main.class.getClassLoader(), 
                                        new Class[] { 
                                            Runnable.class, 
                                            Comparable.class,
                                        }, 
                                        handler);

        runnable = (Runnable)object;
        runnable.run();

        comparable = (Comparable<Object>)object;
        comparable.compareTo("Hello");
    }
}
+7
source

Source: https://habr.com/ru/post/1705443/


All Articles