
aQute.json.codec.ObjectHandler Maven / Gradle / Ivy
package aQute.json.codec;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class ObjectHandler extends Handler {
@SuppressWarnings("rawtypes")
final Class rawClass;
final FDesc fields[];
final FDesc extra;
static class FDesc implements Comparable {
boolean optional;
String name;
Field field;
Type type;
Object deflt;
boolean skip;
@Override
public int compareTo(FDesc o) {
return name.compareTo(o.name);
}
}
ObjectHandler(JSONCodec codec, Class> c) throws Exception {
rawClass = c;
List fields = new ArrayList<>();
FDesc x = null;
Object template;
try {
template = c.newInstance();
} catch (Exception e1) {
template = null;
}
for (Field f : c.getFields()) {
if (Modifier.isStatic(f.getModifiers()))
continue;
FDesc fdesc = new FDesc();
fdesc.field = f;
fdesc.type = f.getGenericType();
fdesc.name = codec.renamer.apply(f);
fdesc.skip = f.getName().startsWith("__");
if (f.getType() == Optional.class) {
ParameterizedType ptype = (ParameterizedType) fdesc.type;
fdesc.type = ptype.getActualTypeArguments()[0];
fdesc.optional = true;
}
if (f.getName().equals("__extra"))
x = fdesc;
if (template != null) {
try {
fdesc.deflt = fdesc.field.get(template);
} catch (Exception e) {
// Ignore
}
}
fields.add(fdesc);
}
if (x != null && Map.class.isAssignableFrom(x.field.getType()))
extra = x;
else
extra = null;
Collections.sort(fields);
this.fields = fields.toArray(new FDesc[fields.size()]);
}
@Override
public void encode(Encoder app, Object object, Map
© 2015 - 2025 Weber Informatics LLC | Privacy Policy