I’m currently writing a serialization-function and have been making progress for everything that doesn’t use an array with primitive types. Here is my code:
import java.lang.reflect.Field;
class BClass {
int value;
BClass(int val) {
value=val;
}
public int getValue() {
return value;
}
}
class AClass {
int value;
BClass c=new BClass(1);
public int getValue() {
return value;
}
}
void setup() {
AClass j=new AClass();
//works
fullSerialize(j, 0);
println("\n\n");
//works
Float m[][]={{1.0, 0.0}, {0.0, 1.0}};
fullSerialize(m, 0);
println("\n\n");
//doesn't work
float m2[][]={{1.0, 0.0}, {0.0, 1.0}};
fullSerialize(m2, 0);
}
void fullSerialize(Object ob, int offset) {
String offs="";
for (int i=0; i<offset; i++) offs+=" ";
assert offset<9;
//check if array
if (ob.getClass().isArray()) {
println(offs+ob.getClass().getSimpleName()+" :");
for (Object i : (Object[]) ob) {
fullSerialize(i, offset+1);
}
} else if (ob==null||ob instanceof Number||ob instanceof String) {
println(offs+ob.getClass().getSimpleName(), ob);
} else {
String[][] fields=fields(ob);
Object[] fi=fieldVals(ob);
for (int i=0; i<fields.length-1; i++) {
if (fi[i]==null||fi[i] instanceof Number||fi[i] instanceof String) {
println(offs+fields[i][0], fields[i][1], fi[i]);
} else {
println(fields[i][0], fields[i][1]+" :");
fullSerialize(fi[i], offset+1);
}
}
}
}
String[][] fields(Object j) {
Field[] field_=j.getClass().getDeclaredFields();
String[][] ret=new String[field_.length][3];
for (int i=0; i<field_.length; i++) {
field_[i].setAccessible(true);
try {
if (field_[i].get(j)!=null) ret[i]=new String[] {field_[i].get(j).getClass().getSimpleName(), field_[i].getName(), field_[i].get(j).toString()};
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return ret;
}
Object[] fieldVals(Object j) {
Field[] field_=j.getClass().getDeclaredFields();
Object[] ret=new Object[field_.length];
for (int i=0; i<field_.length; i++) {
field_[i].setAccessible(true);
try {
ret[i]=field_[i].get(j);
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return ret;
}
The problem is with primitive types not being regarded as objects so when I try to cast to a float[] array to a Object[] array. How can I still make the conversion work?
The problem is without casting the object to a array I can’t look what is inside the array since it is regarded as a object.
PS: I know that there are good serialization-libraries but making one myself sounded like a fun idea.