java反射访问另一个类中通过接口声明的对象的方法
在下面的代码中,我将 Printer1 类型作为接口(IPrinter)类型,但我实际上希望它作为打印机类类型。
在 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();
}
}
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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您有一个
Slot
对象,并且希望通过反射获取其printer1
成员变量,那么您应该能够这样做:If you have a
Slot
object and through reflection you want to get at itsprinter1
member variable, you should be able to do that like this:由于插槽中的打印机字段是公共的,因此您应该能够以正常方式获取实例。 (插槽.打印机1)
Since the printer-field in the Slot is public, you should be able to get the instance in a normal way. (slot.printer1)