Search code examples
javauno

Deleting fields in Open Office UNO Java api


I wanted to delete text fields I have previously inserted into my .odt document. In content.xml they look like:

<text:user-field-decls>
    <text:user-field-decl text:name="id" office:string-value="${baza.id}" office:value-type="string"/>
    ...
</text:user-field-decls>

Since, as I've read Here the way to delete something is to cast it to interface that has dispose() method I have tried the following code :

XTextFieldsSupplier xTextFieldsSupplier = (XTextFieldsSupplier) UnoRuntime.queryInterface(
            XTextFieldsSupplier.class, xDoc);
XNameAccess xNamedFieldMasters = xTextFieldsSupplier.getTextFieldMasters();
Object fieldMaster = xNamedFieldMasters.getByName("com.sun.star.text.fieldmaster.User."+name);
((XComponent)fieldMaster).dispose()

Where name is the name of field I wanted to delete. I assume that the field is not used anywhere in the document besides declaration. However that throws ClassCast exception:

java.lang.ClassCastException: com.sun.star.uno.Any cannot be cast to com.sun.star.lang.XComponent

on the last line. And if that's the case, how can I delete the field?


Solution

  • And I found it - class casting is not the way to access the interface I need, querying UNO is. So the answer to my question is:

    XComponent comp = UnoRuntime.queryInterface(XComponent.class,fieldMaster);
    comp.dispose();