How to iterate through the objects of a class and its member classes using Java

17,129
public void getAllClassAndFields() {
    ObjectFactory objectFactory = new ObjectFactory();
    Method[] methods = objectFactory.getClass().getDeclaredMethods();
    for (Method method : methods) {
        try {
            // Check if method have XmlElementDecl annotation
            XmlElementDecl annotation = method.getAnnotation(XmlElementDecl.java);
            if (annotation == null) {
                // Invoke method only if it is not annoatated with XmlElementDecl 
                Object object = method.invoke(objectFactory, new Object[] {});
                System.out.println("Class Name = " + object.getClass().getName());
                printFileds(object);
            }

        } catch (Exception e) {
          // I used Exception to keep it simple, instead use appropriate exception types here 
        } 
    }
}

public static void printFileds(Object obj) {
    Field[] fields = obj.getClass().getFields();
    for (Field field : fields) {
        System.out.println("Field Name = " + field.getName());
    }
}
Share:
17,129

Related videos on Youtube

VictorCreator
Author by

VictorCreator

Wannabe saint!

Updated on October 10, 2022

Comments

  • VictorCreator
    VictorCreator over 1 year

    I'm trying to get all the data objects(variables alone, not its functions et al) of one class (objectfactory.java) and also, invoke the methods in itself, that create instances of other classes in the same package, and this way, make a list of all the objects in all the classes in a given package. (to put things in perspective, these are classes created by JAXB).

    That is, what I basically want to do is, iterate through, and make a list of all the data objects of:

    Objectfactory, and then,
    - Person
    - Name
    - Url
    - Link
    - Personnel
    

    classes.

    Here is the objectFactory class:

    @XmlRegistry
    public class ObjectFactory {
    
        private final static QName _Given_QNAME = new QName("", "given");
        private final static QName _Email_QNAME = new QName("", "email");
        private final static QName _Family_QNAME = new QName("", "family");
    
        /**
         * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: schema
         * 
         */
        public ObjectFactory() {
        }
        public Person createPerson() {
            return new Person();
        }
    
        public Name createName() {
            return new Name();
        }
    
        public Url createUrl() {
            return new Url();
        }
    
        public Link createLink() {
            return new Link();
        }
    
        public Personnel createPersonnel() {
            return new Personnel();
        }
    
        @XmlElementDecl(namespace = "", name = "given")
        public JAXBElement<String> createGiven(String value) {
            return new JAXBElement<String>(_Given_QNAME, String.class, null, value);
        }
        @XmlElementDecl(namespace = "", name = "email")
        public JAXBElement<String> createEmail(String value) {
            return new JAXBElement<String>(_Email_QNAME, String.class, null, value);
        }
    
        @XmlElementDecl(namespace = "", name = "family")
        public JAXBElement<String> createFamily(String value) {
            return new JAXBElement<String>(_Family_QNAME, String.class, null, value);
        }
    
    }
    

    I could go directly only until the fields and methods in ObjectFactory using Java Reflections.(getDeclaredFields()) etc.

    But, for the other classes, I can only manually reach their objects. (For eg, for Class Link)

    ObjectFactory factory= new ObjectFactory();
    Field[] fields = factory.createLink().getClass().getDeclaredFields();
    
            Field[] fields1 = factory.createPerson().getClass().getDeclaredFields();
    
            for (Field f1 : fields1) {
                System.out.println("field name = " + f1.getName()); 
            }
    

    but, I want to do this at runtime for all the classes in objectfactory, and not manually by making calls like "createPerson()".

    I tried doing something like this;

    ObjectFactory factory= new ObjectFactory();
      Method[] methods = factory.getClass().getDeclaredMethods();
         for (Method m : methods) {
    System.out.println("Class name = " + m.getName()); 
            Field[] subfields = m.getClass().getDeclaredFields();
    
    
            for (Field sf : subfields) {
                System.out.println("entities = " + sf.getName()); 
            }
            System.out.println("\n\n");
    
        }
    

    But this doesn't work.

    My expected output would be something like this:

    Class name = ObjectFactory
        field name = _Given_QNAME
        field name = _Email_QNAME
        field name = _Family_QNAME
    
    Class name = Person
        field name = Name
        field name = Age
        field name = Sex
    
    Class name = Personnel
        field name = address
     ...
    

    and so on..

    How do I do this?

  • VictorCreator
    VictorCreator almost 11 years
    Thanks for your response. really helped me! But, I used the response above as it is better suited to my needs! :)
  • Ajinkya
    Ajinkya almost 11 years
    @Vijairam: Glad I could help!