• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 606
  • Last Modified:

NoSuchFieldException using Reflection

I am trying to use reflection to loop through an instantiated class objects public fields. I keep getting "Unhandled exception type NoSuchFieldException" . I have been following the article below. However I am new to Java & Relection. Could anyone point out my issue ?

http://java.sun.com/docs/books/tutorial/reflect/member/fieldValues.html


               Class<?> c = dto.getClass();
            
            Field[] myfields;
            myfields = new Field[100];
            myfields = c.getFields();
            
            for(int i = 0; i < myfields.length; i++)
            {
                  System.out.println(myfields[i].getName());
                  Field chap = c.getDeclaredField(myfields[i].getName());
                  System.out.println(chap.get(dto));
            }
0
acousticsatelite
Asked:
acousticsatelite
1 Solution
 
objectsCommented:
>                   Field chap = c.getDeclaredField(myfields[i].getName());

thats unnecesary, can just be:

                  Field chap = myfields[i];
0
 
Bart CremersJava ArchitectCommented:
You need to make sure you handle checked exception correctly, or rethrow them when you can't handle them. Handling exceptions is done using a try-catch block. The method getDeclaredField can throw a NoSuchFieldException and thus needs to be handled. Also "chap.get(dto)" can throw an IllegalAccessException, so an additional catch block is necessary.

Further, there are some unnecessary things in your code.

    Class<?> c = dto.getClass();
           
    Field[] myfields;
    myfields = new Field[100]; // Remove, next line will make this redundant
    myfields = c.getFields();
           
    for(int i = 0; i < myfields.length; i++) {
        System.out.println(myfields[i].getName());
        try {
            Field chap = c.getDeclaredField(myfields[i].getName());  // Field chap = myfields[i]; // As objects pointed out
            System.out.println(chap.get(dto));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now