Commons JXPath

Standard Extension Functions

创建新的对象

JXPathContext context = JXPathContext.newContext(null);
Book book = (Book) context.getValue("com.huey.jxpath.Book.new()");
Author author = (Author) context.getValue("com.huey.jxpath.Author.new('Eric', 'Freeman', 'F', java.util.Date.new())");

调用静态方法

JXPathContext context = JXPathContext.newContext(null);
Book bestBook = (Book) context.getValue("com.huey.jxpath.Book.getBestBook()");

调用普通方法

the target of the method is specified as the first parameter of the function.

JXPathContext context = JXPathContext.newContext(null);
context.getVariables().declareVariable("book", book);
String title = (String) context.getValue("getTitle($book)");

Custom Extension Functions

定义一个格式化类:

package com.huey.jxpath;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MyFormats {
    public static String dateToStr(Date d, String pattern){
        return new SimpleDateFormat(pattern).format(d);
    }    
}

将格式化类注册到 JXPathContext:

JXPathContext context = JXPathContext.newContext(null);
context.setFunctions(new ClassFunctions(MyFormats.class, "formats"));
context.getVariables().declareVariable("today", new Date());
String today = (String) context.getValue("formats:dateToStr($today, 'yyyy-MM-dd')");
原文地址:https://www.cnblogs.com/huey/p/4703383.html