有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing Java反射,投射到未知对象?

基本上,我扫描JFrame中的所有组件,检查它是否有方法setTitle(字符串arg0),如果有,则将其标题设置为“foo”。然而,为了设置它的标题,我需要将它投射到一个合适的对象上

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

问题是,我不知道这是什么课。有没有办法让它自己消失,或者我应该试着做些别的事情


共 (1) 个答案

  1. # 1 楼答案

    for (Method m : c.getClass().getDeclaredMethods()){
        if (m.getName().equals("setTitle")) {
            m.invoke(c, "foo");
        }
    }
    

    删除所有其他不必要的代码。字符串s是无用的(因为无论如何,附加所有方法名并检查contains是没有意义的。如果类中有名为setTitle的方法呢?)