Domanda

I have the following classes:

interface Ivisitor{

    @deduceStrategy("...")
    void visit(Icosmos c);
}

Visitor implements this interface:

class Visitor implements Ivisitor{
        @deduceStrategy("...") 
    public void visit(Icosmos c) 
    {
        ....
    }
}

The dynamic proxy:

public class strategyLoader{
    public static <T> T  create(Class<T> clazz,Object wrap) {
       T object = (T) Proxy.newProxyInstance(strategyLoader.class.getClassLoader(), new Class[] { clazz },new Handler(wrap)); 
       return object;

    }
}

Relevant portion of the handler class:

public class Handler implements InvocationHandler {
 Object obj;
 public Handler(Object obj) {
 this.obj = obj;
 }

public Object invoke(Object proxy, Method m, Object[] args)
            throws Throwable {
        if (m.isAnnotationPresent(deduceStrategy.class)) {
     Class[] parameterTypes = m.getParameterTypes();
     if((parameterTypes.length==1)&&(**Icosmos.class.isInstance(parameterTypes[0])**))
         {
            ........
         }

I need to load the appropriate strategy based on the exact type of Icosmos passed into Visitor.visit. However,the parameter[0] is never resolving to an instance of Icosmos. Would appreciate if someone showed me the way out. The client invokes visitor as:

Ivisitor visitor = strategyLoader.create(Ivisitor.class,Visitor.class.newInstance());
È stato utile?

Soluzione

Icosmos.class.isInstance(parameterTypes[0])

is exactly equivalent to parameterTypes[0] instanceof Icosmos, and checks whether the object parameterTypes[0] is an instance of Icosmos (which it isn't - it's a java.lang.Class).

There are two possibilities for what you really need. One would be

Icosmos.class.isAssignableFrom(parameterTypes[0])

which checks whether the class parameterTypes[0] is assignment-compatible with Icosmos, i.e. given an x which is an instance of the class represented by parameterTypes[0], would

Icosmos foo = x;

be legal without a cast. This would check that the declared type of the first formal parameter is compatible with Icosmos.

The second alternative would be

args[0] instanceof Icosmos

which checks the runtime type of the actual argument value rather than the declared type of the formal parameter.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top