2012-02-01 46 views
0

在我的代碼中,我得到了printer1類型作爲接口(IPrinter)類型,但我實際上希望它作爲打印機類類型。通過java反射在另一個類中的接口聲明的對象的訪問方法

在JavaReflectionTrial.accessPrinter()我有2個給插槽參數不是打印機

是有可能在JavaReflectionTrial獲得打印機的打印機對象。

interface IPrinter { 
    void enable(); 
} 

class Printer implements Iprinter { 
    void enable() { 
    //doSomething; 
    } 
} 

class Slot { 
    public IPrinter printer1 = new Printer(); 
} 

class JavaReflectionTrial { 
    accessPrinter(Slot slot) { 
    class cls=slot.getclass(); 
    field[] fields=cls.getfields(); 
    } 
} 

回答

0

如果你有Slot對象,並通過反射你想在其printer1成員變量,你應該能夠做到這一點是這樣的:

Class<?> cls = slot.getClass(); 
Field field = cls.getDeclaredField("printer1"); 

// Get the value of the printer1 member variable in slot 
Printer printer = (Printer)field.get(slot); 
+0

現在我明白了謝謝 – 2012-02-01 14:33:49

0

由於在打印機場插槽是公開的,您應該能夠以正常方式獲取實例。 (slot.printer1)

+0

實際上我想要2訪問打印機在運行時,所以只有我米使用反射 – 2012-02-01 14:21:42

相關問題