[英]Java8+: Pass Anonymous Object to Method
How can I pass an anonymous Object to a method (in an other class) and read the data like in the non-working example below?如何将匿名 Object 传递给方法(在其他类中)并像下面的非工作示例中那样读取数据?
public static void caller() {
Object obj = new Object() { final String name = "Aloha from Hawaii"; };
consumer(obj);
}
public static void consumer(Object obj) {
System.out.println(obj.name);
}
Regarding to the link provided by jdabtieu:关于 jdabtieu 提供的链接:
public static void consumer(Object obj) {
try {
System.out.println(obj.getClass().getDeclaredField("name").get(obj));
} catch (NoSuchFieldException | IllegalAccessException ignored) {
}
}
Is it really that complicated?真的有那么复杂吗? However, it's working - and if there is no better solution I'll stay with it.
但是,它正在工作 - 如果没有更好的解决方案,我会继续使用它。
Many thanks非常感谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.