Creating a class using Generics

Posted on 2009-02-23
Last Modified: 2012-05-06
I have a task which is to take the element of an xml file and create a class by the name of the element and pass the attributes as parameters of the constructor of that class.
If the element is Abc a class by name Abc should be formed. The xml may consist of different elements at different times. I thought of approaching the issue using generics as the name of the class is not known ahead of time. I am getting it. Could anyone help me out of this.
//After parsing the xml file the following method should generate the class   

 public void generateClassNode()


        String xmlFile="Member.xml";

        Node classNode=null;

        Document doc=null;

        System.out.println("Entered generate class node");

        NodeFilter filter = new NodeFilter() {

        public short acceptNode(Node n) {

        if (n.getNodeType() == Node.ATTRIBUTE_NODE || n.getNodeType()==Node.ELEMENT_NODE)


          if (((Text) n).getData().trim().length() == 0)

            return NodeFilter.FILTER_REJECT;


        return NodeFilter.FILTER_ACCEPT;




    int whattoshow = NodeFilter.SHOW_ELEMENT & NodeFilter.SHOW_ATTRIBUTE;




        System.out.println("Before traversal ...");

        DocumentTraversal docTraverse =(DocumentTraversal)doc;

        TreeWalker twlk = docTraverse.createTreeWalker(doc.getDocumentElement(), whattoshow, filter, false);

        System.out.println("Before for loop");

        Node rootnode = twlk.getRoot();

        //NodeList nlist = rootnode.getChildNodes();

        NodeList nlist = doc.getElementsByTagName("*");

        System.out.println("The size of node list is "+ nlist.getLength());       

        //for(Node n=twlk.firstChild(); twlk.lastChild()=null; n=twlk.nextSibling())

        for(int i=0;i<nlist.getLength();i++)


            System.out.println("Inside for loop");

            Node n=nlist.item(i);


            if(n.getNodeType()==Node.ELEMENT_NODE || n.getNodeType()==Node.ATTRIBUTE_NODE)


                String element=n.getNodeName();






                HashMap attributeBucket = new HashMap();

                String element=n.getNodeName();

                String value=n.getNodeValue();

                System.out.println(element+"= "+value); 






   //The following code generates the class of the string name

    void generateClass(String className)


        String classStr=generateUcasechar(className);

        Class<T> tclass;

        tclass = (<T>)Class.forName(classStr);




    //Following class changes the first char of the string into upper case to be suitable   //for the being created as class

    String generateUcasechar(String className)


        StringBuilder name = new StringBuilder(className);

        name.setCharAt(0, (char)(name.charAt(0) -32));

        for(int i = 1 ; i < name.length() ; i++){

            if(name.charAt(i -1) == ' ' && name.charAt(i) != ' '){

                name.setCharAt(i, (char)(name.charAt(i) -32));



        return name.toString();


Open in new window

Question by:rmvprasad
    LVL 86

    Expert Comment

    I wouldn't reinvent the wheel. Commons Digester will do this for you, along with a host of other things

    Author Comment

    Thanks. I have looked to it. Could you please explain it with using Generics so I can get used to generics.

    Author Comment

    Another main reason for not showing intrest in common Digester is it is using xpath. So the path and the element needs to be known ahead of time. Here in my case it needs to generate a class based on the name of the element. Common Digester sample code is pasted below.

        Digester digester = new Digester();
        // This method pushes this (SampleDigester) class to the Digesters
        // object stack making its methods available to processing rules.
        // This set of rules calls the addDataSource method and passes
        // in five parameters to the method.
        digester.addCallMethod("datasources/datasource", "addDataSource", 5);
        digester.addCallParam("datasources/datasource/name", 0);
        digester.addCallParam("datasources/datasource/driver", 1);
        digester.addCallParam("datasources/datasource/url", 2);
        digester.addCallParam("datasources/datasource/username", 3);
        digester.addCallParam("datasources/datasource/password", 4);
        // This method starts the parsing of the document.
      // Example method called by Digester.
      public void addDataSource(String name,
                                String driver,
                                String url,
                                String userName,
                                String password)
    LVL 92

    Expert Comment

    its not really appropriate for generics. with generics you can wite code to operate on different classes of objects, but you need to be able to pass the type involved.

    eg. to crete a collection you need to know what type of collection you want.

    List s = new ArrayList();

    LVL 86

    Accepted Solution

    It might be possible to use an API for unmarshalling using reflection

    Author Closing Comment


    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    Suggested Solutions

    Title # Comments Views Activity
    Issues installing SSL certificate into Apache Tomcat 3 48
    stringclean challenge 26 43
    wordappend challenge 8 47
    JAVA part two 4 10
    For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
    Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
    Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
    This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now