私のコードで何が間違っているのか分かりますか?Javaリフレクションキャストの問題
まず私はctype関数値(ONEP_ONEC)を取得したい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;
}
}
このクラスを持っている
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);
}
}
テスト・タイプの結果がnullで、私は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 任意の提案ですか? あなたは明らかに2つの異なるCType
クラス、de.daisi.async.infrastructure.comunicationtype
でde.daisi.async.infrastructure.component.event
パッケージに1つ、他を持って事前
あなたの 'import'は' CheckComType'と 'TemperatureEvent'のように見えますか? – bradimus
異なるパッケージには、 'de.daisi.async.infrastructure.component.event.CType'と' de.daisi.async.infrastructure.comunicationtype.CType'という2つのCTypeクラスがあります。それらを混ぜないようにしてください。残念ながら、あなたが輸入品を含めなかったので、見るのは難しいです。 – vempo
コメントに詳しい情報を入れないでください。代わりにあなたの質問を更新してください! – GhostCat