0

I have a custom class called Trip that has a couple of getter methods, everything public. I add several Trip objects to a ArrayList:

public ArrayList<Trip> routeIndex;

When calling back one of these Trip objects with the following code, I incur a access error.

    Trip abc = routeIndex.get(0);
    for (Field field : abc.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        String name = field.getName();
        field.setAccessible(true);
        Object value = field.get(abc);
        System.out.printf("Field name: %s, Field value: %s%n", name, value);
    }

This is the following error on the Object value line:

unreported exception java.lang.IllegalAccessException; must be caught or declared when thrown

Any ideas where I might be going wrong?

RMass
  • 177
  • 1
  • 2
  • 14
  • This is called *checked exception*. You must wrap a `try/catch` block around those calls. – Paulo Mattos May 18 '17 at 02:32
  • Also, you may declare `throws` on the function in order to allow the application to compile without changing its behaviour. – ktbiz May 18 '17 at 03:06
  • How does "I'm getting a compiler error" translate to the "Java Arraylist loses methods/fields on get()" of your title? – Jon Skeet May 18 '17 at 04:15

1 Answers1

1

You should add try/catch block around filed.get(abc) cause the method filed.get(Object obj) would throw IllegalAccessException and you should handle with it.

So you just need change the Object value = field.get(abc); to

Object value = null;
try {
    value = field.get(abc);
} catch (IllegalAccessException e) {
    e.printStackTrace();
}

and it works fine.

HowieChih
  • 340
  • 3
  • 11