Reputation: 302
I have 2 auto-generated packages (generated by JAXB) from XML schema's that are controlled by a third party. They have sections of their XML definitions that are identical. Some of those sections I will be using to gather information for processing the XML. How can I go about this to reduce the amount of code duplication?
I want to be able to create methods I can call more generically. The following would be an example of the two methods that have been generated:
com.example.xml1 o = (com.example.xml1) u.unmarshal(document);
String type1 = o.getRoot().getType();
com.example.xml2 o = (com.example.xml2) u.unmarshal(document);
String type2 = o.getRoot().getType();
Is there a method I can use where I could get the object and call:
// magic somewhere in here
//Object o = u.unmarshal(document);
String type = o.getRoot().getType();
I won't know the XML type until I am able to read that part. Would using xPath to read the form type and then branching based on that be the best way to do this?
Upvotes: 1
Views: 394
Reputation: 1353
As Garrett Hall answered, you could use reflection to accomplish this. Here's a working example that uses reflection to invoke the getType() method from objects of two different types:
package com.example;
public class MainProgram {
public static void main(String[] args) throws Exception {
XML1 x1 = new XML1("Foo");
XML2 x2 = new XML2("Bar");
String type1 = (String) x1.getClass().getMethod("getType").invoke(x1);
String type2 = (String) x2.getClass().getMethod("getType").invoke(x2);
System.out.println("type1 = " + type1);
System.out.println("type2 = " + type2);
}
}
class XML1 {
private String type;
public XML1(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
class XML2 {
private String type;
public XML2(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Upvotes: 1
Reputation: 30022
If you cannot modify the generated code, then you can use reflection or subclass both classes and have them implement the same interface, so that they can be treated similarly.
Upvotes: 1
Reputation: 31795
As long as classes xml1 and xml2 have a common super class (or interface) that has getRoot() method you will be able to call it on both of them without additional casting. You should be able to do that by making a common type for xml1 and xml2 element in your xml schema.
Upvotes: 0