How to invoke JSF action on an anonymous class? EL cannot access it

后端 未结 2 1230
离开以前
离开以前 2021-01-02 16:47

I want to have a generic menu in my JSF (MyFaces 1.2) application.


  

        
2条回答
  •  忘掉有多难
    2021-01-02 17:27

    That's because anonymous classes are not accessible from outside the package containing the anonymous class.

    Here's a demonstration what's happening behind the scenes:

    public static void main(String[] args) throws Exception {
        Portal portal = new Portal();
        Object list = portal.getClass().getDeclaredMethod("getActionList", null).invoke(portal, null);
        Object action = list.getClass().getDeclaredMethod("get", new Class[] { int.class }).invoke(list, 0);
        action.getClass().getDeclaredMethod("action", null).invoke(action, null);
    }
    

    Try executing this in the same package as Portal class and then once again in another class outside the package. In the other package, the last line would then throw exactly the same exception. That's the problem EL is struggling with since it's based on reflection.

    I don't see other ways to solve this nicely than just creating a public (inner) class. Reflection (and thus also EL) can access them from other packages.

    public class Portal {
    
        private List list = new ArrayList();
    
        public Portal() {
            list.add(new IActionImpl());
        }
    
        public class IActionImpl implements IAction {
            public void action() {
                System.out.println("called action here");
            }
        }
    
        public List getActionList() {
            return list;
        }
    
    }
    

提交回复
热议问题