reflection - Java type conversion where types are not known until runtime -


I am trying to write data access layer for an AJAX web project. This is to convert DAL to the data coming through the AJAX servlet into an object, which can be sent to the space prepared for the execution.

The data in the AJAX servlet, as the strings received using the HTTPEVERATOR.JetParameter (...).

In each data class, I have a known set of fields as well as their data types, e.g. CustomerId (integer), customer name (string)

I can write a method in Customer Class to handle the conversion, but that means I have to do it for each Data Object Class. I am very much a normal method that converts, like

  object convert (string value, class & lt ?? & gt; TargetType) {...}  < / Pre> 

Can someone tell me in the right direction?

Create a utility class with all conversion methods, within its static initial, parameter type And use the reflection to collect all those methods by return type in the map. Then, in the conversion () method, only select the method that is suitable for the given source and the target type and apply it. Use generic to fix the type of return similar to the target type. :

  public stable   

JSON is also an interesting option. You can send AJAX all the parameters as a JSON string. After that, you can use the JSON-to-Javabean converter such as converting a JSON string to a full-width webbian like client . It will be as simple as:

  string jsondata = request.getParameter ("jsondata"); Client Client = New GSN () JSON (Jessondata, Customer.class); // ...  

See also for another example.


Comments