0

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?

Grim
  • 1,938
  • 10
  • 56
  • 123
  • From JDK documentation I see that `getProxyClass` accepts a list of interfaces as vararg. Isn't it what you want? If it is, then you just need to dynamically create the list of interfaces to pass to `getProxyClass`. Am I misunderstanding something? – Raffaele Rossi Jan 16 '14 at 14:28

1 Answers1

0

Proxy.getProxyClass accepts 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 invoke toArray(T[]) to convert the list to an array

List<Class> interfaces = new LinkedList<Class>();
interfaces.add(Animal.class);
if (cage.animal instanceof Run) {
    interfaces.add(Run.class);
}
if (cage.animal instanceof Fly) {
    interfaces.add(Fly.class);
}

Proxy.getProxyClass(cl, interfaces.toArray(new Class[interfaces.size()]));
Grim
  • 1,938
  • 10
  • 56
  • 123
Raffaele Rossi
  • 1,079
  • 5
  • 11