mercredi 10 août 2016

java reflection casting issue

I wonder if you can see what is wrong with my code.

First I have this class

package de.daisi.async.infrastructure.component.event;
import static de.daisi.async.infrastructure.component.event.CType.*;

public class TemperatureEvent implements IEvent {

private static final long serialVersionUID = 1L;
private CType cType = ONEP_ONEC;

public String toString(){
    return "TemperatureEvent";
}


public CType getcType() {
    return cType;
}
}

Via java reflection I want to get the CType value (ONEP_ONEC)

package de.daisi.async.infrastructure.comunicationtype;
import de.daisi.async.infrastructure.component.event.*;
import java.lang.reflect.Method;

public class CheckComType {

public CType checkType(Class<? extends IEvent> eventClass) {
    System.out.println("Check communcationType: " + eventClass);

    CType cType = null;

    try {
        System.out.println("---In Try---");
        Class cls = (Class) eventClass;
        System.out.println("cls: " + cls);

        Method method = cls.getDeclaredMethod("getcType");
        System.out.println("method: " + method);
        Object instance = cls.newInstance();

        cType = (CType) method.invoke(instance);
        System.out.println("instance: " + instance);
        System.out.println("cType: " + cType);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return cType;

}

public static void main(String... args){
    CheckComType type = new CheckComType();
    CType testType = type.checkType(TemperatureEvent.class);
    System.out.println("testType: " + testType);

}

}

The testType result is null and I got a ClassCastException

java.lang.ClassCastException: de.daisi.async.infrastructure.component.event.CType cannot be cast to de.daisi.async.infrastructure.comunicationtype.CType at de.daisi.async.infrastructure.comunicationtype.CheckComType.checkType at de.daisi.async.infrastructure.comunicationtype.CheckComType.main

Any suggestions? Thank you in advance





Aucun commentaire:

Enregistrer un commentaire