org.klojang.path.ObjectReader Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of klojang-invoke Show documentation
Show all versions of klojang-invoke Show documentation
Klojang Invoke is a Java module focused on path-based object access and dynamic
invocation. Its central classes are the Path class and the PathWalker class. The
Path class captures a path through an object graph. For example
"employee.address.city". The PathWalker class lets you read from and write to
a wide variety of types using Path objects.
The newest version!
package org.klojang.path;
import java.util.Collection;
import java.util.Map;
import static org.klojang.util.ClassMethods.isPrimitiveArray;
import static org.klojang.path.PathWalkerException.nullValue;
final class ObjectReader {
private final boolean se;
private final KeyDeserializer kd;
ObjectReader(boolean suppressExceptions, KeyDeserializer keyDeserializer) {
this.se = suppressExceptions;
this.kd = keyDeserializer;
}
Object read(Object obj, Path path, int segment) {
if (segment == path.size()) {
return obj;
} else if (obj == null) {
return deadEnd(nullValue(path, segment));
} else if (obj instanceof Collection c) {
return new CollectionSegmentReader(se, kd).read(c, path, segment);
} else if (obj instanceof Object[] o) {
return new ArraySegmentReader(se, kd).read(o, path, segment);
} else if (obj instanceof Map m) {
return new MapSegmentReader(se, kd).read(m, path, segment);
} else if (isPrimitiveArray(obj)) {
return new PrimitiveArraySegmentReader(se, kd).read(obj, path, segment);
}
return new BeanSegmentReader(se, kd).read(obj, path, segment);
}
Object deadEnd(PathWalkerException.Factory excFactory) {
if (se) {
return null;
}
throw excFactory.get();
}
}