Java-反射,转换为未知对象? [英] Java - Reflection, casting to an unknown Object?
本文介绍了Java-反射,转换为未知对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基本上,我浏览了JFrame中的所有组件,检查它是否具有方法setTitle(String arg0),如果有,则将其标题设置为 foo。但是,为了设置标题,我需要将其转换为合适的对象。
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?
推荐答案
当您拥有方法
,您可以使用 invoke()
进行调用:
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
}
}
这篇关于Java-反射,转换为未知对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文