简体   繁体   中英

Java IllegalAccessException

I got a problem with IllegalAccessException in my program

here's my code

    private static void setdata(Field field, Object dto, Object value) throws IllegalArgumentException, IllegalAccessException {
    boolean accessible = field.isAccessible();
    if (!accessible)
        field.setAccessible(true);
    if (value instanceof java.lang.String) {
        if (value != null) {
            value = String.valueOf(value).trim();
        }
    }
    field.set(dto, value);
    if (accessible)
        field.setAccessible(false);
}

to prevent 'IllegalAccessException' I added check logic.

boolean accessible = field.isAccessible();' if (!accessible) field.setAccessible(true);

but sometimes a IllegalAccessException is occured in my program.

the Exception raised on the line - 'field.set(dto, value);'

The Exception is as belows

java.lang.IllegalAccessException: Class com.comm.util.FileReadUtils can not access a member of class com.dto.myDto with modifiers "private"

At first, I think the 'static' is might be problem.

but as far as I know, static method do make own stack frame when it is called.

so I got nothing.

please let me know what did I do something stupid~

my program runs on Spring 3.x and java 1.6

public static void setField(Object object, String fieldName, Object fieldValue)
{
    try
    {
        Field field = object.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(object, fieldValue);
    }
    catch(Exception exception)
    {
        // Log error
    }
}

Please try the above code and it should work(I didn't compiled this, check for syntax errors if any) How did you got the Field instance? There might be some issues in that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM