java 反射 强制转换,Java-反射,转换为未知对象?

该篇博客讲述了如何遍历JFrame中的所有组件,通过检查它们的方法是否存在`setTitle`,然后调用`invoke`方法来设置组件标题为'foo',避免了强制类型转换的困扰。作者探讨了解决在不明确组件类型的情况下进行方法调用的问题。
摘要由CSDN通过智能技术生成

Basically, I scan through all components in a JFrame, checking if it has the method setTitle(String arg0), if it does, then set it's title to "foo". However, in order to set it's title I need to cast it to a suitable object.

public void updateTitle(Container root){

for (Component c : root.getComponents()){

String s = "";

for (Method m : c.getClass().getDeclaredMethods()){

s += m.getName();

}

if (s.contains("setTitle")){

c.setTitle("foo"); //Here is where I need the casting

}

if (c instanceof Container){

updateTitle((Container) c);

}

}

}

Problem is, I don't know what class is it. Is there any way to cast it to itself, or I should try doing something else?

解决方案

When you have a Method, you can use invoke() to call it:

for (Method m : c.getClass().getDeclaredMethods()){

if( "setTitle".equals( m.getName() ) {

m.invoke( c, "foo" ); // == c.setTitle("foo"); but without the casts

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值