use of suite.inspect.Inspect in project suite by stupidsing.
the class Object_ method mapper.
public static Mapper mapper(Type type) {
Mapper mapper;
if (type instanceof Class) {
Class<?> clazz = (Class<?>) type;
if (Type_.isSimple(clazz))
mapper = new Mapper(object -> object, object -> object);
else if (clazz.isArray()) {
Class<?> componentType = clazz.getComponentType();
mapper = new Mapper(object -> {
Map<Object, Object> map = new HashMap<>();
int length = Array.getLength(object);
for (int i = 0; i < length; i++) map.put(i, Array.get(object, i));
return map;
}, object -> {
Map<?, ?> map = (Map<?, ?>) object;
Object objects = Array.newInstance(componentType, map.size());
int i = 0;
while (map.containsKey(i)) {
Array.set(objects, i, map.get(i));
i++;
}
return objects;
});
} else if (// polymorphism
clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers()))
mapper = new Mapper(object -> {
Class<?> clazz1 = object.getClass();
Object m = apply_(mapper(clazz1).map, object);
if (m instanceof Map) {
@SuppressWarnings("unchecked") Map<String, String> map = (Map<String, String>) m;
map.put("@class", clazz1.getName());
return map;
} else
// happens when an enum implements an interface
return m;
}, object -> {
if (object instanceof Map) {
Map<?, ?> map = (Map<?, ?>) object;
String className = map.get("@class").toString();
Class<?> clazz1 = Rethrow.ex(() -> Class.forName(className));
return apply_(mapper(clazz1).unmap, object);
} else
// happens when an enum implements an interface
return object;
});
else {
Inspect inspect = Singleton.me.inspect;
List<Pair<String, Field>> sfs = //
Read.from(//
inspect.fields(clazz)).map(//
field -> Pair.of(field.getName(), field)).toList();
mapper = new Mapper(object -> Rethrow.ex(() -> {
Map<Object, Object> map = new HashMap<>();
for (Pair<String, Field> sf : sfs) map.put(sf.t0, sf.t1.get(object));
return map;
}), object -> Rethrow.ex(() -> {
Map<?, ?> map = (Map<?, ?>) object;
Object object1 = new_(clazz);
for (Pair<String, Field> sf : sfs) sf.t1.set(object1, map.get(sf.t0));
return object1;
}));
}
} else if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
Type rawType = pt.getRawType();
Class<?> clazz = rawType instanceof Class ? (Class<?>) rawType : null;
if (List.class.isAssignableFrom(clazz))
mapper = new Mapper(object -> {
Map<Object, Object> map = new HashMap<>();
int i = 0;
for (Object o : (Collection<?>) object) map.put(i++, o);
return map;
}, object -> {
Map<?, ?> map = (Map<?, ?>) object;
Collection<Object> object1 = new ArrayList<>();
int i = 0;
while (map.containsKey(i)) object1.add(map.get(i++));
return object1;
});
else if (Map.class.isAssignableFrom(clazz))
mapper = new Mapper(object -> object, object -> object);
else
mapper = mapper(rawType);
} else
mapper = Fail.t("unrecognized type " + type);
return mapper;
}
Aggregations