I wonder what is the best way to delete an element without knowing its type?
I've tried a solution, which looks for the parents getContent() and returns this list as return value. The user than can invoke the remove method on this list. Does another generic method already exist in the framework? Otherwise we could try to add such a feature in docx4j?!
Here is my code:
Using java Syntax Highlighting
@SuppressWarnings("unchecked")
public List<Object> getParentContent(Child child) throws DocxProcessorException {
Child parent = null;
Class<?> parentClass = null;
Method contentMethod = null;
do {
// get parent element
parent = (Child) child.getParent();
// get class info
parentClass = parent.getClass();
try {
// try to find a getContent method
contentMethod = parentClass.getDeclaredMethod("getContent"); //$NON-NLS-1$
} catch (NoSuchMethodException e) {
// parent gets new child
child = parent;
}
// if method was found or body is reached
} while (contentMethod == null && !(parent instanceof Body));
if (contentMethod != null) {
// invoke getContent at parent element
Object retObj = null;
try {
retObj = contentMethod.invoke(parent);
} catch (IllegalArgumentException e) {
throw new DocxProcessorException("Error invoking the getContent method of the parent.", e); //$NON-NLS-1$
} catch (IllegalAccessException e) {
throw new DocxProcessorException("Error invoking the getContent method of the parent.", e); //$NON-NLS-1$
} catch (InvocationTargetException e) {
throw new DocxProcessorException("Error invoking the getContent method of the parent.", e); //$NON-NLS-1$
}
if (!(retObj instanceof List<?>)) {
return null;
}
return (List<Object>) retObj;
}
return null;
}
public List<Object> getParentContent(Child child) throws DocxProcessorException {
Child parent = null;
Class<?> parentClass = null;
Method contentMethod = null;
do {
// get parent element
parent = (Child) child.getParent();
// get class info
parentClass = parent.getClass();
try {
// try to find a getContent method
contentMethod = parentClass.getDeclaredMethod("getContent"); //$NON-NLS-1$
} catch (NoSuchMethodException e) {
// parent gets new child
child = parent;
}
// if method was found or body is reached
} while (contentMethod == null && !(parent instanceof Body));
if (contentMethod != null) {
// invoke getContent at parent element
Object retObj = null;
try {
retObj = contentMethod.invoke(parent);
} catch (IllegalArgumentException e) {
throw new DocxProcessorException("Error invoking the getContent method of the parent.", e); //$NON-NLS-1$
} catch (IllegalAccessException e) {
throw new DocxProcessorException("Error invoking the getContent method of the parent.", e); //$NON-NLS-1$
} catch (InvocationTargetException e) {
throw new DocxProcessorException("Error invoking the getContent method of the parent.", e); //$NON-NLS-1$
}
if (!(retObj instanceof List<?>)) {
return null;
}
return (List<Object>) retObj;
}
return null;
}
Parsed in 0.018 seconds, using GeSHi 1.0.8.4