I use instanceof to test for capabilitys.
interface Animal{}
class AnimalImpl{}
class Cage{
public Animal animal;
}
If i have a Cage cage with a Animal and like to add a Proxy for Fly and Run to the Animal
interface Fly{}
interface Run{}
I do the following
01 ClassLoader cl = class.getClassLoader();
02 cage.animal = new AnimalImpl();
03
04 // Add fly
05 Class proxyFly = Proxy.getProxyClass(cl, Animal.class, Fly.class);
06 cage.animal = (Animal) proxyFly.getConstructor(new Class[]{InvocationHandler.class}).newInstance(ih);
07
08 // Add run
09 Class proxyFly = Proxy.getProxyClass(cl, Animal.class, Run.class);
10 cage.animal = (Animal) proxyFly.getConstructor(new Class[]{InvocationHandler.class}).newInstance(ih);
11 assert cage.animal implements Fly;
Line 11 fails. In line 09 i need to add Fly.class but is there no dynamic way?
Proxy.getProxyClassaccepts a varargs of interfaces. Just build up an array of classes to pass to it. If you're not sure at compile time of which or how many interfaces to pass, then you might store them into a list and then invoketoArray(T[])to convert the list to an array