I'm working on an Android app, and I'm developing on my Macbook laptop when I'm away from home and my Windows computer at home. I have the same JDK version (1.8.0_131) on both machines, and I have set the correct JDK path like shown here: How to set the JDK in Android Studio.
When I call the method Class.getDeclaredFields() on either machine, I get very different results. On my Mac, the method behaves similarly to how the Java-Doc says it should, although it seems to only see public fields. When testing on my Windows computer, the method returns ALL fields, even inherited ones, which is explicitly what the Java-Doc says the method DOES NOT do. I need Class.getDeclaredFields() to be consistent because I'm using it to build JSON files with Gson and store them on the disk elsewhere in my program.
I'm guessing that there is a different Android Runtime which is causing the program to behave differently, but I have no idea where to find that information or how to correct this problem so that it runs consistently when deployed.
On both machines I'm using a Nexus 5X virtual device with Android API 25 (Android 7.1.1 Nougat) and build tools 25.0.2.
Here's my specific implementation:
public abstract class Article {
protected Context context;
protected int id;//start at 0 and go up.
private Texture texture;
private Temperature idealTemp;
private Formality formality;
private String name;
private int color; //expressed as hex RGB
private Bitmap image;
JsonObject articleData;
...
@Override
public String toString() {
//TODO: for efficiency, this should be StringBuilder
String temp = "id: " + id + ", texture: " + texture + ", idealTemp: " + idealTemp
+ ", formality: " + formality + ", name: " + name + ", color: #" + color;
Field[] fields = this.getClass().getDeclaredFields();
for (Field f : fields) {
try {
temp = temp.concat(", " + f.getName() + ": " + f.get(this).toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
continue;
}
}
return temp;
}
}//end class
Where the class that inherits Article is Top which looks like this:
public abstract class Top extends Article {
public Top(Context con, Texture tex, Temperature temp, Formality form, String n, int col, Bitmap img) {
super(con, tex, temp, form, n, col, img);
}
}
And finally the non-abstract class that uses the method Article.toString() is Shirt:
public class Shirt extends Top {
//If this is not public, it is not seen by getDeclaredFields()
//seems to be a bug in the Android Runtime on my Mac?
public boolean longSleeves;
public Shirt(Context con, Texture tex, Temperature temp, Formality form,
String n, int col, Bitmap img, boolean longSleeve) {
super(con, tex, temp, form, n, col, img);
longSleeves = longSleeve;
}
}
UPDATE: The code I originally posted used
getFields()
instead of
getDeclaredFields()
This has been changed and I will include images to show what both of my debuggers in Android Studio show:
Mac: