`。
*
* @author cyq
* @version V1.0
* @since V1.0
*/
public class ObjectPathUtil {
public record Rule(String targetPath, String mvelExpr) {}
public sealed interface PathSeg permits KeySeg, IndexSeg {}
public record KeySeg(String key) implements PathSeg {}
public record IndexSeg(int index) implements PathSeg {}
public static List parsePath(String path) {
List result = new ArrayList<>();
int i = 0;
while (i < path.length()) {
if (path.charAt(i) == '.') {
i++;
continue;
}
if (path.charAt(i) == '[') {
int end = path.indexOf(']', i);
int index = Integer.parseInt(path.substring(i + 1, end));
result.add(new IndexSeg(index));
i = end + 1;
} else {
int start = i;
while (i < path.length()
&& path.charAt(i) != '.'
&& path.charAt(i) != '[') {
i++;
}
result.add(new KeySeg(path.substring(start, i)));
}
}
return result;
}
public static Object putValue(Object root, List path, Object value) {
if (root == null) {
root = (path.get(0) instanceof IndexSeg) ? new ArrayList<>() : new HashMap<>();
}
Object current = root;
for (int i = 0; i < path.size(); i++) {
PathSeg seg = path.get(i);
boolean last = (i == path.size() - 1);
if (seg instanceof KeySeg keySeg) {
Map map = castMap(current);
if (last) {
map.put(keySeg.key(), value);
} else {
Object next = map.get(keySeg.key());
if (next == null) {
next = createNext(path.get(i + 1));
map.put(keySeg.key(), next);
}
current = next;
}
}
if (seg instanceof IndexSeg indexSeg) {
List