javaarraylistmethodsillegalaccessexception

Java Arraylist loses methods/fields on get()


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?


Solution

  • 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.