1
I cannot read the attributes values of the class 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 to field.get(this)
and still passing the instance of the object field.get(model)
Model object attributes are not private. If you do not use the method field.setAccessible(true);
the exception is the same.
At the request of friend Ramaral, follows 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;
}
}
That code doesn’t even compile.
– ramaral
I don’t know much about Reflection, but I think you need to prevent Exception with Try in dynamic methods, so compile, but do not perform accordingly. If you have suggestions with other methods or Pattern
– Ericson
Yes you have to put the Try/catch but the line
values.put(field.getName(), field.get(this.getClass()));
will continue to make a mistake. On its ownfield.get(this.getClass())
should not be an error. Edit the question and put the class attributes.– ramaral