Java - Reflection, casting to an unknown Object?

2019-08-02 18:25发布

问题:

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