我已经编写了一个自定义内置函数以在我的项目中使用,但我真的不知道如何使用它。
我已经写了两门课了。其中一个是我制作的内置函数(使用 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
的结果 - 调用示例
内置
的结果
...这正是我们所看到的:
[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]
关于java - 一旦我编写了内置函数,我需要做什么才能让推理机意识到它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23268298/