繁体   English   中英

Java反射铸造问题

[英]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;
}
}

通过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结果为null,我得到了ClassCastException

java.lang.ClassCastException:de.daisi.async.infrastructure.component.event.CType无法转换为de.daisi.async.infrastructure.comunicationtype.CheckComType.checkType处的de.daisi.async.infrastructure.comunicationtype.CType .daisi.async.infrastructure.comunicationtype.CheckComType.main

有什么建议么? 先感谢您

您显然有两个不同的CType类,一个在de.daisi.async.infrastructure.component.event包中,另一个在de.daisi.async.infrastructure.comunicationtype 由于您没有在CheckComType明确引用de.daisi.async.infrastructure.component.event.CTypeCheckComType将使用同一包中的类(即de.daisi.async.infrastructure.comunicationtype.CType )。

在Java中,重要的是全类名。 包本质上是名称空间,即使名称相同,属于不同包的类也是不同的类。

de.daisi.async.infrastructure.component.event.CType cType = null;

try {

    //...
    cType = (de.daisi.async.infrastructure.component.event.CType) method.invoke(instance);
}

等等。

或者,如果您不想在同一个类中同时使用两个CTypeimport de.daisi.async.infrastructure.component.event.CTypeCheckComType显式import de.daisi.async.infrastructure.component.event.CType CheckComType

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM