ClassCastException when casting to the same class

前端 未结 11 942
小蘑菇
小蘑菇 2020-11-22 07:09

I have 2 different Java projects, one has 2 classes: dynamicbeans.DynamicBean2 and dynamic.Validator.

On the other project, I load both of

11条回答
  •  醉梦人生
    2020-11-22 08:02

    I got the A2AClassCastException problem when trying to create a List of objects from XML using Apache Commons Digester.

    List templates = new ArrayList();
    Digester digester = new Digester();
    digester.addObjectCreate("/path/to/template", MyTemplate.class);
    digester.addSetNext("/path/to/template", "add");
    // Set more rules...
    digester.parse(f); // f is a pre-defined File
    
    for(MyTemplate t : templates) { // ClassCastException: Cannot cast mypackage.MyTemplate to mypackage.MyTemplate
        // Do stuff
    }
    

    As stated above, the cause is that the digester doesn't use the same ClassLoader as the rest of the program. I ran this in JBoss, and it turned out that commons-digester.jar was not in JBoss's lib directory, but rather in a webapp's lib directory. Copying the jar into mywebapp/WEB-INF/lib also solved the problem. Another solution was to casll digester.setClassLoader(MyTemplate.class.getClassLoader()), but that feels like quite an ugly solution in this context.

提交回复
热议问题