2

我已经编写了一个自定义内置函数以在我的项目中使用,但我真的不知道如何使用它。我写了两节课。其中一个是我制作的内置函数(使用BaseBuiltin),另一个是我注册了新的内置函数(使用BuiltinRegistry)。

我已经尝试过使用默认的内置函数,并在使用 Java 的 Eclipse 可读的文本文件中编写使用它们的规则。在这种情况下,我没有任何问题。我怎样才能使用我已经建立的内置?我应该在某些文件中导入(或包含)某些内容吗?

4

1 回答 1

3

首先,您Builtin通常通过扩展来定义 a ,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);

此代码的输出将是:

  • 前向链接规则的字符串
  • 调用打印的结果 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]
于 2014-04-24T13:50:00.310 回答