aQute.lib.json.ObjectHandler Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of bndlib Show documentation
Show all versions of bndlib Show documentation
The bndlib project is a general library to be used with OSGi bundles. It contains
lots of cool functionality that calculates dependencies, etc.
package aQute.lib.json;
import java.lang.reflect.*;
import java.util.*;
public class ObjectHandler extends Handler {
@SuppressWarnings("rawtypes")
final Class rawClass;
final Field fields[];
final Type types[];
final Object defaults[];
final Field extra;
ObjectHandler(@SuppressWarnings("unused") JSONCodec codec, Class< ? > c) throws Exception {
rawClass = c;
fields = c.getFields();
// Sort the fields so the output is canonical
Arrays.sort(fields, new Comparator() {
public int compare(Field o1, Field o2) {
return o1.getName().compareTo(o2.getName());
}
});
types = new Type[fields.length];
defaults = new Object[fields.length];
Field x = null;
for (int i = 0; i < fields.length; i++) {
if (fields[i].getName().equals("__extra"))
x = fields[i];
types[i] = fields[i].getGenericType();
}
if (x != null && Map.class.isAssignableFrom(x.getType()))
extra = x;
else
extra = null;
try {
Object template = c.newInstance();
for (int i = 0; i < fields.length; i++) {
defaults[i] = fields[i].get(template);
}
}
catch (Exception e) {
// Ignore
}
}
@Override
void encode(Encoder app, Object object, Map