I have a requirement where the user specifies the class names to be loaded along with the constructor parameters, in the following manner in a XML file.
<websocket>
<ip>localhost</ip>
<port>8887</port>
</websocket>
<MessageBusClient>
<BarCodeScanner>
<param>MessageBus</param>
<param>CommunicationInterface</param>
<param>int</param>
<param>int</param>
</BarCodeScanner>
</MessageBusClient>
According to the given format, I need to instantiate the BarcodeScanner class calling the constructor which has the above mentioned parameters. So I came up with the code give below. I iterate through each class and add the parameters to a list. Then I thought of getting the constructors of the class through reflection and compare the parameters each take, with the list of parameters I loaded from XML.
NodeList nListMBC = doc.getElementsByTagName("MessageBusClient");
Node tempNode = nListMBC.item(0);
if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
Node childNode = tempNode.getChildNodes().item(1);
System.out.println(childNode.getNodeName());
NodeList classNodes = tempNode.getChildNodes();
for (int classCount = 1; classCount < classNodes.getLength() - 1; classCount++) {
if (classNodes.item(classCount).getNodeType() == Node.ELEMENT_NODE) {
classNames.add(classNodes.item(classCount).getNodeName());
try {
Class classToLoad = messageBusClientsLoader
.loadClass(classNodes.item(classCount).getNodeName());
NodeList paramNodes = classNodes.item(classCount).getChildNodes();
for (int paramCount = 1; paramCount < paramNodes.getLength() - 1; paramCount++) {
if (paramNodes.item(paramCount).getNodeType() == Node.ELEMENT_NODE)
parameters.add(paramNodes.item(paramCount).getTextContent());
if (paramCount == paramNodes.getLength() - 1) {
try {
Constructor[] constructors = classToLoad.getConstructors();
for(Constructor c : constructors){
//compare the constructor parameters and parameters array list. If matching constructor found, create the instance.
}
} catch (SecurityException | DOMException e) {
System.out
.println("Exception when trying to invoke constructor : " + e.getMessage());
}
}
}
} catch (ClassNotFoundException ex) {
System.out.println("class not found" + ex.getMessage());
}
}
}
}
As you can see the code looks very complicated and clumsy. Is there any other alternative way of achieving this? Your advice is much appreciated.
Aucun commentaire:
Enregistrer un commentaire