【问题标题】:String cannot be cast to javax.jcr.Value字符串不能转换为 javax.jcr.Value
【发布时间】:2020-01-09 10:08:20
【问题描述】:

当我尝试使用以下代码为 JCR 节点设置属性时,我收到以下错误 String cannot be cast to javax.jcr.Value。 javax.jcr.Node.setProperty(String name, Value value) 需要“value”参数的值,但转换不起作用。

// using for-each loop for iteration over Map.entrySet() 
for (Entry<String, Object> entry : map.entrySet()) { 
    try {
        //fetch the value of uuid mapped to the key "jcr:uuid"
        String uuid= (String) map.get("jcr:uuid");
        //get the JCR workspace session value for website
        Session session = MgnlContext.getJCRSession(RepositoryConstants.WEBSITE);
        //get the JCR node specified by the given identifier
        Node node = session.getNodeByIdentifier(uuid);

        //verify if the value for the specific value is of type HashMap
        //this means we have a nested map which denotes another node
        if (entry.getValue() instanceof HashMap ) {
            System.out.println("New node: " + entry.getKey());
            //Creates a new node at relPath of the specified node type
            node.addNode(entry.getKey(),NodeTypes.Page.NAME);
            //initializes a new map that points to the nested map
            HashMap<String , Object> newmap = (HashMap<String, Object>) entry.getValue();
            //recursion happens here
            loadMap(newmap);

        } else {
            //Sets the single-value property for all entries to the specified value.

            node.setProperty(entry.getKey(), (Value)entry.getValue()); ---> *error here*
            System.out.println("Key = " + entry.getKey() + 
                            ", Value = " + entry.getValue()); 
        }       
    } catch (ItemNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (RepositoryException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

感谢@Ducaz035,这是解决方案

String value= (String)entry.getValue();
node.setProperty(entry.getKey(), value);

【问题讨论】:

  • 嗯,我觉得这个信息是不言自明的。您不能将字符串强制转换为对象 Value。也许尝试使用 Value 的构造函数?
  • 您在map 中添加了什么?根据错误消息,这些是Strings,因此无法转换为 Value。
  • 我正在尝试将一个字符串放入一个值中。该错误非常不言自明,但我不知道解决方法是什么。我得到的值是一个字符串。
  • 您是否尝试过使用ValueFactory.createValue(java.lang.String value)?这就是我能够找到的,但我从未使用过 JCR,所以我不知道它是否有效。

标签: java jcr magnolia


【解决方案1】:

相信你可以直接使用javax.jcr.Node#setProperty(java.lang.String, java.lang.String)。实际上,它接受 String 作为值。

您的代码中的问题不在于 String 或 Value,而是您尝试插入 Object,可能将 Object 转换为 String,然后设置属性

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-27
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多