我最终得到的解决方案如下。由于时间限制,我最终使用了 reg-ex 方法(直到最近我才看到关于这个问题的其他建议)
这可能不是最好的方法,但它似乎运作良好(我已经使用一个测试套件对其进行了审查,该套件可以练习我此时需要处理的用例)。
该createStatement(...)
方法位于 OntUtilities 助手类中。
/**
* Serialization output method.
*
* @param out
* @throws IOException
*/
private void writeObject(final ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject(_statement.getSubject().getURI());
out.writeObject(_statement.getPredicate().getURI());
out.writeObject(_statement.getObject().toString());
}
/**
* deserialization method.
*
* @param in
* @throws IOException
* @throws ClassNotFoundException
*/
private void readObject(final ObjectInputStream in) throws IOException,
ClassNotFoundException {
in.defaultReadObject();
final String subject = (String)in.readObject();
final String predicate = (String)in.readObject();
final String object = (String)in.readObject();
_statement = OntUtilities.createStatement(subject, predicate, object);
}
/**
* Creates a statement from a triple of strings. These strings may be fully
* qualified uris, or shortened "namespace" uris (eg: shai:TST)
*
* @param sub The resource uri (the subject)
* @param pred The predicate uri (the property)
* @param ob The object uri.
* @return A JENA Statement.
*/
public static Statement createStatement(final String sub, final String pred,
final String ob) {
final Model m = ModelFactory.createDefaultModel();
final String s = OntUtilities.nsUriToUri(sub);
final String p = OntUtilities.nsUriToUri(pred);
final String o = OntUtilities.nsUriToUri(ob);
Statement stmt = null;
try {
// try making a uri as a syntax-verification step.
new URI(o);
// it was valid, so well use o as a resource:
final Resource obj = m.createResource(o);
stmt = m.createStatement(m.createResource(s), m.createProperty(p), obj);
} catch (final URISyntaxException e) {
// o was *not* a uri.
if (o.contains("^^")) {
final int idx = o.lastIndexOf("^^");
final String value = o.substring(0, idx);
final String uri = o.substring(idx+2);
final Literal lit = m.createTypedLiteral(value, getDataType(uri));
stmt = m.createStatement(m.createResource(s), m.createProperty(p), lit);
} else {
// just use the string as-is:
stmt = m.createStatement(m.createResource(s), m.createProperty(p), o);
}
}
return stmt;
}