Fields in java, "not a primitive field" error

McD0n3ld

I have been working with Fields for parsing a class to a SharedPreferences. It worked while the settings class was not a Singleton. I changed to work as a Singleton and it is not working anymore.

G2ASettings settings = G2ASettings.getInstance();
    Field[] fields = G2ASettings.class.getDeclaredFields();
    for (Field f : fields) {
        f.setAccessible(true);
        try {
            if (preferences.contains(f.getName()) && !f.getName().equals("INSTANCE")) {
                f.set(settings, preferences.getBoolean(f.getName(), f.getBoolean(settings))); //si no lo encuentra, pone el valor por defecto determinado en la clase
            } else {
                if (blablabla) {
                    editor.putBoolean(f.getName(), true);
                    allPreferencesDisabled = true;
                } else
   (*)----->        editor.putBoolean(f.getName(), f.getBoolean(settings)); 
            }
   (*)----->  if (!allPreferencesDisabled) allPreferencesDisabled = f.getBoolean(settings);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

The error reported is the following:

Caused by: java.lang.IllegalArgumentException: not a primitive field

The error is repoted at lines marked as (*) in the code.

The fields of G2ASettings are all public and boolean except INSTANCE variable which is G2ASettings type variable and is private.

I will be reporting here my progress.

EXTRA: I post here only relevant data of G2ASettings class (usual Singleton class):

public class G2ASettings implements Serializable {

public boolean {big amount of boolean variables]

private static G2ASettings INSTANCE = null;
private synchronized static void createInstance() {
    if (INSTANCE == null) {
        INSTANCE = new G2ASettings();
    }
}

public static G2ASettings getInstance() {
    if (INSTANCE == null) createInstance();
    return INSTANCE;
}

{public getters and setters}
}
Tim

Which field is the one you're on when it throws this exception? I'd bet money it's INSTANCE, which as you said isn't a Boolean so you can't call getBoolean() on it.

Your if statement that checks if the current field is not INSTANCE before trying to get its Boolean value needs to be earlier and cover all of your other logic, since INSTANCE is never going to have a Boolean value and shouldn't be persisted.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related