我已经在我的项目中编写了一个自定义内置程序,但我真的不知道如何使用它.
我写过两节课.在其中一个中有我使用的内置(使用BaseBuiltin),另一个我注册了新的内置(使用BuiltinRegistry).
我已经尝试使用默认的内置函数,编写在使用Java从Eclipse可读的文本文件中使用它们的规则.在这种情况下,我没有任何问题.我怎样才能使用我建的内置?我应该在某些文件中导入(或包含)某些内容吗?
解决方法:
首先定义一个Builtin,通常通过扩展BaseBuiltin,然后使用BuiltinRegistry.theRegistry.register(Builtin)使其可用于基于Jena规则的推理.
完成后,您需要实际使用一个引用您的Builtin的规则来触发它.
BuiltinRegistry.theRegistry.register( new BaseBuiltin() {
@Override
public String getName() {
return "example";
}
@Override
public void headAction( final Node[] args, final int length, final RuleContext context ) {
System.out.println("Head Action: "+Arrays.toString(args));
}
} );
final String exampleRuleString =
"[mat1: (?s ?p ?o)\n\t-> print(?s ?p ?o),\n\t example(?s ?p ?o)\n]"+
"";
System.out.println(exampleRuleString);
/* I tend to use a fairly verbose syntax for parsing out my rules when I construct them
* from a string. You can read them from whatever other sources.
*/
final List<Rule> rules;
try( final BufferedReader src = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(exampleRuleString.getBytes()))) ) {
rules = Rule.parseRules(Rule.rulesParserFromReader(src));
}
/* Construct a reasoner and associate the rules with it */
final GenericRuleReasoner reasoner = (GenericRuleReasoner) GenericRuleReasonerFactory.theInstance().create(null);
reasoner.setRules(rules);
/* Create & Prepare the InfModel. If you don't call prepare, then
* rule firings and inference may be deferred until you query the
* model rather than happening at insertion. This can make you think
* that your Builtin is not working, when it is.
*/
final InfModel infModel = ModelFactory.createInfModel(reasoner, ModelFactory.createDefaultModel());
infModel.prepare();
/* Add a triple to the graph:
* [] rdf:type rdfs:Class
*/
infModel.createResource(RDFS.Class);
此代码的输出将是:
>前向链规则的字符串
>调用print Builtin的结果
>调用示例Builtin的结果
……这正是我们所看到的:
[mat1: (?s ?p ?o)
-> print(?s ?p ?o),
example(?s ?p ?o)
]
-2b47400d:14593fc1564:-7fff rdf:type rdfs:Class
Head Action: [-2b47400d:14593fc1564:-7fff, http://www.w3.org/1999/02/22-rdf-syntax-ns#type, http://www.w3.org/2000/01/rdf-schema#Class]