jena

How to get the class of an individual using Jena?


I have a class Joy in my ontology. It has individuals Happy, Glad etc. The isDefinedBy Annotation property of Happy states Joy. Now I wanted to get the class name (or URI) for any individual passed, so I tried getOntClass() method for the individual, but didn't get the required result. Then I tried getIsDefinedBy() method and got this.

Exception in thread "main" com.hp.hpl.jena.ontology.ConversionException: Cannot convert node "Joy" to OntResource
at com.hp.hpl.jena.ontology.impl.OntResourceImpl$1.wrap(OntResourceImpl.java:79)
at com.hp.hpl.jena.enhanced.EnhNode.convertTo(EnhNode.java:152)
at com.hp.hpl.jena.enhanced.EnhNode.convertTo(EnhNode.java:31)
at com.hp.hpl.jena.enhanced.Polymorphic.asInternal(Polymorphic.java:62)
at com.hp.hpl.jena.enhanced.EnhNode.as(EnhNode.java:107)
at com.hp.hpl.jena.ontology.impl.OntResourceImpl.objectAs(OntResourceImpl.java:1411)
at com.hp.hpl.jena.ontology.impl.OntResourceImpl.objectAsResource(OntResourceImpl.java:1421)
at com.hp.hpl.jena.ontology.impl.OntResourceImpl.getIsDefinedBy(OntResourceImpl.java:395)
at myPackage.Ontology.load(Ontology.java:90)
at myPackage.MyClass.main(MyClass.java:75)

Here's the code I used

Individual indiv = mod.getIndividual(namespace + "Happy");
//System.out.println(indiv.getOntClass());
System.out.println(indiv.getIsDefinedBy());

What should I do?


Solution

  • From what I know of Jena (I've been working with it for 3 months now) you are misunderstanding the meaning of URI. URI stands for Unique Resource Identificator or something similar, so that 2 individuals of the same OntClass would have different URIs but the same OntClass.

    Correct me if I'm wrong but you want to get this OntClass the individuals belong to, right? If it is the OntClass you want to retrieve my personal solution to the matter was to use the property type of the rdf namespace.

    OntModel m = ModelFactory.createOntModel();
    m.read("file:///" + ontologyPath);
    string RDF = m.getNsPrefixURI("rdf");
    string namespace = m.getNSPrefixURI(yourOntologyPrefix);
    Property type = m.getProperty(RDF, "type");
    Individiual indiv = m.getIndividual(namespace + "Happy");
    if (indiv.getPropertyResourceValue(type).toString().Equals(namespace + "Joy"))
        println("you got it");
    else
        println("this is not joy :(");
    

    May not be the most elegant way to do it but well :D