tags:

views:

316

answers:

1

Weird question...

How can I make use of Java's Invocation Interceptor like when using Dynamic Proxies without actually having a target object?

For example, I'd like to make an uber object that can stand in for a dozen or so interfaces specified at runtime without necessarily needing an object that implements any of them.

Basically this'd work like the __call functionality from most dynamic languages.

Thoughts?

+5  A: 

Perhaps I am misunderstanding the question (if so please let me know!) 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");
    }
}
TofuBeer
If it's that simple, I'm seriously kicking myself.
Allain Lalonde
well the return (0) thing gets a bit tricky - you have to return the appropriate type for each method (so null for run and in for compareTo). Also what you can do in the compareTo isn't all that clear to me :-) but beyond that I believe it is that simple.
TofuBeer
Worked like a charm
Allain Lalonde
I always knew that knowledge would come in handy one day... :-)
TofuBeer