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.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()]));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top