我不知道你是否能看到我的代码有什么问题。java反射投射问题
首先,我有这个类
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;
}
}
通过Java反射我想要得到的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被转换为 de.daisi.async.infrastructure.comunicationtype.CType。在de.daisi.async.infrastructure.comunicationtype.CheckComType.main
任何建议comunicationtype.CheckComType.checkType ? 预先感谢您
你在'CheckComType'和'TemperatureEvent'中的输入''看起来像什么? – bradimus
在不同的包中有两个CType类:'de.daisi.async.infrastructure.component.event.CType'和'de.daisi.async.infrastructure.comunicationtype.CType'。确保你不要混合它们。不幸的是,你很难看到,因为你没有包括进口。 – vempo
不要把更多的信息放入评论。请更新您的问题! – GhostCat