Интересно, можете ли вы увидеть, что не так с моим кодом.java reflection casting issue
Сначала я этот класс
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 Я хочу, чтобы получить значение CType (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);
}
}
Результат TestType является недействительным и Я получил ClassCastException
java.lang.ClassCastException: de.daisi.async.infrastructure.component.event.CType не может быть приведен к de.daisi.async.infrastructure.comunicationtype.CType на de.daisi.async.infrastructure. comunicationtype.CheckComType.checkType на de.daisi.async.infrastructure.comunicationtype.CheckComType.main
Любые предложения? Спасибо заранее
Что вы видите '' '' '' '' '' '' в 'CheckComType' и' TemperatureEvent'? – bradimus
У вас есть два класса CType в разных пакетах - 'de.daisi.async.infrastructure.component.event.CType' и' de.daisi.async.infrastructure.comunicationtype.CType'. Убедитесь, что вы не смешиваете их. К сожалению, это трудно понять, поскольку вы не включили импорт. – vempo
Не помещайте дополнительную информацию в комментарии. Обновите свой вопрос! – GhostCat