Java - Reflection, casting to an unknown Object?

2019-08-02 18:39发布

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?

3条回答
闹够了就滚
2楼-- · 2019-08-02 19:09

You can call setTitle() via reflection, not via casting

查看更多
叛逆
3楼-- · 2019-08-02 19:17
for (Method m : c.getClass().getDeclaredMethods()){
    if (m.getName().equals("setTitle")) {
        m.invoke(c, "foo");
    }
}

Delete all other unnecessary code. Your String s is useless (because anyway, it makes no sense to append all method names and check for contains. What if the class had methods called setT and itle?)

查看更多
劫难
4楼-- · 2019-08-02 19:28

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
     }
 }
查看更多
登录 后发表回答