I'm facing an issue while trying to use Java reflection.
I have a PermanentObject class, that implements a general method to turn an object into a JSON string (the syntax is not yet completely implemented so glide past it)
This is the code of the method:
@Override
public String toFileFormat() {
String info = "";
try {
Class myClass = this.getClass();
Class mySuperclass = myClass.getSuperclass();
Field[] superclassFields = mySuperclass.getDeclaredFields();
Field[] myFields = myClass.getDeclaredFields();
info += "{\n";
for (int i = 0; i < superclassFields.length; i++) {
myFields[i].setAccessible(true);
info += "\"" + superclassFields[i].getName() + "\":\"" + superclassFields[i].get(this) + "\",\n";
}
for (int i = 0; i < myFields.length; i++) {
myFields[i].setAccessible(true);
info += "\"" + myFields[i].getName() + "\":\"" + myFields[i].get(this) + "\"";
if (i < myFields.length - 1) info += ",";
info += "\n";
}
info += "}";
} catch (Exception e) {
e.printStackTrace();
}
return info;
}
I then have a User abstract subclass that extends PermanentObject, and a Professor subclass that extends User.
When invoking the method tho I get this error: java.lang.IllegalAccessException: class esercizio2.permanence.PermanentObject cannot access a member of class esercizio2.logic.users.User with modifiers "private"
I was wondering why this is
I can solve the problem by implementing the method in the User class rather than in the PermanentObject class, but this leads to duplication of code since there are other PermanentObject subclasses that will need to use this.
Thanks for the help :>
Aucun commentaire:
Enregistrer un commentaire