2016-08-10 204 views
0

我不知道你是否能看到我的代码有什么问题。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 ? 预先感谢您

+0

你在'CheckComType'和'TemperatureEvent'中的输入''看起来像什么? – bradimus

+1

在不同的包中有两个CType类:'de.daisi.async.infrastructure.component.event.CType'和'de.daisi.async.infrastructure.comunicationtype.CType'。确保你不要混合它们。不幸的是,你很难看到,因为你没有包括进口。 – vempo

+1

不要把更多的信息放入评论。请更新您的问题! – GhostCat

回答

1

您显然有两个不同的CType类,一个在de.daisi.async.infrastructure.component.event包和另一个在de.daisi.async.infrastructure.comunicationtype。由于您没有明确提及CheckComType中的de.daisi.async.infrastructure.component.event.CType,因此使用来自相同包(即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); 
} 

等等。

或者只是明确地import de.daisi.async.infrastructure.component.event.CTypeCheckComType如果你不打算同时使用两个CType的类。

+0

谢谢!现在解决了,我没有意识到我有两个CType类... :) – andreahg

+0

太棒了!您可以将其标记为已回答。我希望这也能回答你的问题(在评论中)如何宣布进口。 – vempo