IllegalAccessException when reading values with reflection

1

I can not read the values of the class attributes with reflection:

    ContentValues values = new ContentValues();

    Field[] fields = this.getClass().getDeclaredFields();

    for (Field field: fields ) {
        field.setAccessible(true);
        values.put(field.getName(), field.get(this.getClass()));
    }

I have the exception: IllegalAccessException in the get method: field.get(this.getClass()) I also tried field.get(this) and still passing the instance of object field.get(model)

The attributes of the model object are not private. If you do not use the field.setAccessible(true); method, the exception is the same.

At the request of your friend Ramaral, follow the whole class:

public class GenericModel {

    public Long id;

    public ContentValues GetContentValues()
    {
        ContentValues values = new ContentValues();

        Field[] fields = this.getClass().getDeclaredFields();

        for (Field field: fields ) {
            field.setAccessible(true);

            try {
                values.put(field.getName(), field.get(this.getClass()));
            } catch (IllegalAccessException e) {

            }
        }

        return values;
    }
}
    
asked by anonymous 04.03.2017 / 20:22

1 answer

1

You have 3 things wrong with your code:

  • The Field # get () method returns an object, it is necessary to cast to a type that the ContentValues # put () accepts and this type must be compatible with the type of attribute in question.

    (Long)field.get(...)
    
  • The Field # get () method must be passed to the object containing the attribute represented by this field and whose value is to be obtained.

    (Long)field.get(this)
    
  • The id attribute must be initialized.

    public Long id = 3l;
    
  • The changes will look like this:

    public class GenericModel {
    
        public Long id = 3l;
    
        public ContentValues GetContentValues()
        {
            ContentValues values = new ContentValues();
    
            Field[] fields = this.getClass().getDeclaredFields();
    
            for (Field field: fields ) {
                field.setAccessible(true);
    
                try {
                    values.put(field.getName(), (Long)field.get(this));
                } catch (IllegalAccessException e) {
                    //Faça algo aqui, nem que seja apenas um log
                }
            }
    
            return values;
        }
    }
    

    Note:
    If GenericModel has more attributes and they are not all of type Long you will need to change the GetContentValues() method to handle this situation.

        
    05.03.2017 / 19:43