Java - Reflection, casting to an unknown Object?

拈花ヽ惹草 提交于 2020-01-25 05:09:04

问题


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?


回答1:


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



回答2:


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




回答3:


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?)



来源:https://stackoverflow.com/questions/14319760/java-reflection-casting-to-an-unknown-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!