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
}
}