Search code examples
javagenericsproxy-classes

Proxying with Generics


I use java.lang.reflect.Proxy to proxy objects.

I have this class:

public class TransportableImpl extends Transportable{
  public class OrderInvoker extends InvocationHandler{
           ...
  }
}

Here i build the Proxy:

Transportable t = new TransportableImpl();
Order myOrder = new OrderImpl();
Class proxyClass = Proxy.getProxyClass(getClass().getClassLoader(), Transportable.class, Order.class);
Object serializable = proxyClass.getConstructor(new Class[]{InvocationHandler.class}).newInstance(t.new OrderInvoker(myOrder));

Problem is: Class is raw type and

Class<? extends Order & Transportable> proxyClass =
     (Class<? extends Order & Transportable>) 
     Proxy.getProxyClass(getClass().getClassLoader(), 
     Transportable.class, Order.class);

is hard to read.

Any ideas?


Solution

  • The Proxy#getProxyClass(ClassLoader, Class) method is declared as

    public static Class<?> getProxyClass(ClassLoader loader,
                                         Class<?>... interfaces)
    

    Its return type is therefore Class<?>. The normal syntax would be

    Class proxyClass<?> = Proxy.getProxyClass(getClass().getClassLoader(), Transportable.class, Order.class);
    

    Technically you could do (with a warning)

    public <T extends Order & Transportable> void doSomething() {
        Class<T> proxyClass = (Class<T>) Proxy.getProxyClass(Driver.class.getClassLoader(),
                Transportable.class, Order.class);
    }
    

    but that gains you nothing as you will pretty much never need to use that T variable. The Class class provides very little methods that makes use of it, namely getConstructor(Class...) and newInstance(). But again, the whole point of reflection is that you only know the class types at run time, not at compile time where generics are useful.