Reputation: 2856
I'm trying to use generics to access the field of an object.
For example, if I have an object called myObject
and I know that most of its fields are of the data type float
. So when I call this function getFieldValuesFloat(myObject, new String[]{"id"});
Then I got this error:
java.lang.IllegalAccessException: class se.danielmartensson.tools.GetClassInformation cannot access a member of class se.danielmartensson.entities.LX_Current with modifiers "private"
Here is the code I have problems with:
public static <T> Float[] getFieldValuesFloat(T object, String[] avoidTheseFields) {
String[] fieldNames = getFieldNames(object, avoidTheseFields);
Float[] fieldValues = new Float[fieldNames.length];
int i = 0;
for(String fieldName : fieldNames) {
try {
Field field = object.getClass().getDeclaredField(fieldName);
fieldValues[i] = field.getFloat(object);
i++;
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return fieldValues;
}
And the error focusing on this code row:
fieldValues[i] = field.getFloat(object);
This is weird, because I'm using this method to get the field names. And that method works. It also using generics, but instead, I'm reading the field names only from an object.
public static <T> String[] getFieldNames(T object, String[] avoidTheseFields) {
Field[] fields = object.getClass().getDeclaredFields();
String[] fieldNames = new String[fields.length - avoidTheseFields.length];
List<String> avoidTheseNamesList = Arrays.asList(avoidTheseFields);
int i = 0;
for(Field field : fields) {
String fieldName = field.getName();
if(avoidTheseNamesList.contains(fieldName))
continue;
fieldNames[i] = fieldName;
i++;
}
return fieldNames;
}
Question:
How can I get all values from an arbitary class using generics?
Upvotes: 2
Views: 2829
Reputation: 57174
The field is probably not accessible, you can check that via
field.isAccessible()
and change it via
field.setAccessible(true)
Upvotes: 4
Reputation: 2860
This exception notify you about you have some field that has a private access level and you can't change the value for that field. You should change access level by command:
field.setAccessible(true);
And then try to change its value.
Upvotes: 0