的方法签名Resource.addProperty
被重载。如果您查看Javadoc,您会发现它具有以下多态变体:
addProperty(Property p, RDFNode o)
addProperty(Property p, String o)
addProperty(Property p, String lexicalForm, RDFDatatype datatype)
addProperty(Property p, String o, String l)
第二个变体采用字符串,只是为了方便添加文字值。第一个变体是你想要的。RDFNode
是Resource
, 因此是Individual
,OntClass
等的超类型。所以你需要做的就是传入一个已经是 RDFNode 的值。
具体来说,以下是您如何断言两个人之间的关系:
Individual ai = A.createIndividual(NS+"nameOfIndividualInA");
Individual bi = B.createIndividual(NS+"nameOfIndividualInB");
Property p = A.createObjectProperty( NS + "p" );
// either
ai.addProperty( p, bi );
// or
model.add( ai, p, bi );
更新
作为对评论的回应,这里有一些实际的可运行代码,显示了调用这些 API 方法的各种方式:
package examples;
import java.util.Calendar;
import com.hp.hpl.jena.datatypes.TypeMapper;
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.rdf.model.*;
public class AddPropertiesExample
{
public static final String NS = "http://example.com/test#";
private Property p;
private Resource r, s;
public static void main( String[] args ) {
new AddPropertiesExample().run();
}
public void run() {
Model m = createModel();
// add property values using the Model.add( Resource, Property, RDFNode) signature
m.add( r, p, s );
m.add( r, p, ResourceFactory.createPlainLiteral( "foo" ) );
m.add( r, p, ResourceFactory.createLangLiteral( "le foo", "fr" ) );
m.add( r, p, ResourceFactory.createTypedLiteral( 42 ) );
m.add( r, p, ResourceFactory.createTypedLiteral( Calendar.getInstance() ));
// ditto using the Model.add( Resource, Property, String ) signature
m.add( r, p, "This is a plain literal" );
// ditto using the Model.add( Resource, Property, String, String ) signature
m.add( r, p, "Das foo", "de" );
// ditto using the Model.add( Resource, Property, String, RDFDatatype ) signature
m.add( r, p, "42.42", XSDDatatype.XSDfloat );
m.add( r, p, "2000-01-01",
TypeMapper.getInstance().getTypeByName( "http://www.w3.org/2001/XMLSchema#date" ) );
m.write( System.out, "Turtle" );
}
private Model createModel() {
Model m = ModelFactory.createOntologyModel();
p = m.createProperty( NS + "p" );
r = m.createResource( NS + "r" );
s = m.createResource( NS + "s" );
return m;
}
}
输出:
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
<http://example.com/test#r>
<http://example.com/test#p> "2000-01-01"^^xsd:date ,
"42.42"^^xsd:float ,
"Das foo"@de ,
"This is a plain literal" ,
"2013-10-28T11:46:35.596Z"^^xsd:dateTime ,
"42"^^xsd:int ,
"le foo"@fr ,
"foo" ;
<http://example.com/test#p> <http://example.com/test#s> .