Skip to content

Latest commit

 

History

History
67 lines (47 loc) · 1.9 KB

objectpath.md

File metadata and controls

67 lines (47 loc) · 1.9 KB

ObjectPath

ObjectPath 是构建在表达式引擎的一个应用实例,底层使用表达式解释器Evaluator

案例

@RequiredArgsConstructor
@Getter
public class User {
    
    private final String name;
    private final List<Book> books;
    
    @RequiredArgsConstructor
    @Getter
    public static class Book{
        private final String name;
        private final Double price;
        private final User author;
    }
}

创建数据对象结构:

User user1 = new User("Sam", Collections.emptyList());
User user2 = new User("Bob", Collections.emptyList());

User.Book book1 = new User.Book("Book1", 12.98, user1);
User.Book book2 = new User.Book("Book2", 10.98, user2);

User user = new User("Allen", Arrays.asList(book1, null, book2));

创建 ObjectPath 对象.

import objectpath.io.github.slince.expression.ObjectPath;

// 使用默认的 evaluator 创建 ObjectPath 实例
ObjectPath objectpath = ObjectPath.create(user);

// 简单调用读取属性
assert objectpath.read("$.name").equals("Allen");

// 多层级链式读取
assert objectpath.read("$.books[0].author.name").equals("Sam");

ObjectPath 中路径表达式语法和表达式基本语法是一致的;特殊地地方在于根变量会被默认设置成 $

自定义 ObjectPath 使用的解释器

import objectpath.io.github.slince.expression.ObjectPath;
import io.github.slince.expression.Evaluator;

// 如果你需要扩展的 evaluator
Evaluator evaluator = new Evaluator(someYourExtensions);
ObjectPath objectpath = new ObjectPath(evaluator,yourObject);
objectpath.read("$.the.path.to.your.property");

如何扩展解释器见扩展解释器文档