samedi 10 avril 2021

Access an Object's field values in Java - cannot access a member of class java.lang.IllegalAccessException

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?





Aucun commentaire:

Enregistrer un commentaire