【问题标题】:Access method of a object declared through interface in another class by java reflection通过java反射在另一个类中通过接口声明的对象的访问方法
【发布时间】:2012-02-01 14:04:51
【问题描述】:

在下面的代码中,我将打印机 1 类型作为接口(IPrinter)类型,但我实际上希望它作为打印机类类型。

在 JavaReflectionTrial.accessPrinter() 中,我有 2 个将 Slot 作为参数而不是打印机

是否可以在 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();
  }
}

【问题讨论】:

    标签: java reflection interface


    【解决方案1】:

    如果你有一个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);
    

    【讨论】:

      【解决方案2】:

      由于 Slot 中的打印机字段是公共的,因此您应该能够以正常方式获取实例。 (slot.printer1)

      【讨论】:

      • 实际上我希望在运行时有 2 个访问打印机,所以只有我在使用反射
      猜你喜欢
      • 2023-03-16
      • 2019-05-28
      • 2015-08-17
      • 2016-09-21
      • 1970-01-01
      • 2011-09-19
      • 1970-01-01
      • 1970-01-01
      • 2013-09-18
      相关资源
      最近更新 更多