Java技术问询:如何检查javax.jcr.node节点的属性是否存在?
Hey there! Great question—verifying whether a property exists on a javax.jcr.Node is totally straightforward, and it’s a built-in method you might have overlooked while browsing the JCR 2.0 docs.
The Go-To Solution: hasProperty()
The Node interface includes a simple hasProperty(String propertyName) method that returns a boolean exactly for this purpose. It’s the most efficient and clean way to check for a property’s existence, no messy exception handling required.
Here’s a quick code example to put it into action:
// Assume you've already retrieved your target Node instance Node myContentNode = session.getNode("/path/to/your/target/node"); String propertyToVerify = "my:description"; // Include namespace prefix if your property uses one if (myContentNode.hasProperty(propertyToVerify)) { // Property exists—fetch and work with it Property descProp = myContentNode.getProperty(propertyToVerify); String description = descProp.getString(); System.out.println("Node description: " + description); } else { // Handle the case where the property doesn't exist System.out.println("Description property not found on this node."); }
Important Notes to Remember
- Namespace Prefixes: If your property uses a custom namespace (like
my:in the example), always include the full prefixed name. If you need to resolve a namespace URI to its prefix, you can use the session’s namespace registry:String customNamespaceURI = "http://your-project-namespace.com"; String prefix = session.getNamespacePrefix(customNamespaceURI); String fullPropertyName = prefix + ":description"; - Skip Exception-Based Checks: While you could try fetching the property directly and catching
PropertyNotFoundException, this is not a good practice. Exceptions are meant for unexpected errors, not routine checks—hasProperty()is far more performant.
Just to confirm: This method is absolutely part of the JCR 2.0 Node interface—maybe it was buried in the docs when you looked! Its signature is:
boolean hasProperty(String name) throws RepositoryException;
Hope this clears things up for you!
内容的提问来源于stack exchange,提问作者mrjayviper

