Método de acceso de un objeto declarado a través de la interfaz en otra clase por reflexión de Java

In my code below I get the printer1 type as interface(IPrinter) type but i actually want it as printer class type.

In JavaReflectionTrial.accessPrinter() i have 2 give the Slot as parameter not the printer

is it possible to get printer in JavaReflectionTrial as Printer object.

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();
  }
}

preguntado el 01 de febrero de 12 a las 14:02

2 Respuestas

Si usted tiene una Slot object and through reflection you want to get at its printer1 member variable, you should be able to do that like this:

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);

Respondido 01 Feb 12, 18:02

Since the printer-field in the Slot is public, you should be able to get the instance in a normal way. (slot.printer1)

Respondido 01 Feb 12, 18:02

actually i want 2 access printer in runtime so only i m using reflection - Mohamed Jameel

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.