Java dynamic proxy without target object?

Strange question

How to use Java's call interceptor when using a dynamic proxy without actually owning the target object?

For example, I want to create a super object that can represent more than a dozen interfaces specified at run time, without necessarily needing an object to implement any of them

Basically, this is like most dynamic languages__ The call function is the same

reflection?

Solution

Maybe I misunderstood this question (if so, please tell me!) But will this get you started?

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");
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>