I have an XML defined which provides a payload path to a serialized XML. I would like to take these parameters and create an object and call a method 开发者_StackOverflow中文版in a class. What is the best approach to do this in Java?
XML
<RequestObjectType>com.test.model.QueryType</RequestObjectType>
<Class>com.test.api.Query</Class>
<Method>generalQuery</Method>
public void callRequestViaObj(String payloadXML, String payloadType, String api_className, String method){
Class c_payloadType = Class.forName(payloadType);
Class c_apiClass = Class.forName(api_className);
JAXBElement<c_payloadType> elemreq = (JAXBElement<c_payloadType>) JaxbUtils.XMLtoObj( payloadXML, JAXBContext.newInstance(c_payloadType) );
c_payloadType qreq = (c_payloadType) (elemreq.getValue());
//Would like to do something like this...
c_payloadType.newInstance().callMethod(method).with(qreq);
}
have a look at the reflection-api:
http://java.sun.com/developer/technicalArticles/ALT/Reflection/
section "Invoking Methods by Name"
There are many tools that will do this for you. One of them is Castor.
It looks like you just need to tweak the calls that use the reflection API. Try
c_payloadType.newInstance().getMethod(method, qreq.getClass()).invoke(qreq);
This assumes that c_payloadType
is an instance of Class<?>
and qreq
is the argument you want to pass to the method call. I'm not sure if the JAXB code you've written correctly constructs those two objects.
精彩评论