mardi 3 avril 2018

BeanUtils setProperty throws an IllegalArgumentException

Environment details

I have three projects:

  • Project A: a Java REST service application
  • Project B: a Java client app
  • Project C: a simple list of POJOs

The first two projects have the third as dependency.

Data flow

Project B makes an HTTP request to Project A which replies using a model object of Project C converting it to JSON.

Project B decodes the JSON response using JSONObject and tries to obtain the original POJO object using BeanUtils.

Code example

ExamplePOJO class (part of Project C):

public class ExamplePOJO {

    private String id;

    private AnotherPOJO anotherPOJO;

    public void setId(String id) {
         this.id = id;
    }

    public String getId() {
         return id;
    }

    public void setAnotherPOJO(AnotherPOJO anotherPOJO ) {
         this.anotherPOJO = anotherPOJO ;
    }

    public AnotherPOJO getAnotherPOJO() {
         return anotherPOJO ;
    }

}

Project A example endpoint:

@Path("/sample")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getExampleResponse() {

    try {

        ServiceResponse<ExamplePOJO> response = new ServiceResponse<ExamplePOJO>();

        ExamplePOJO eo = new ExamplePOJO();
        eo.setId("1");

        AnotherPOJO ap = new AnotherPOJO();
        eo.setAnotherPojo(ap);

        response.setResponse(eo);

        return ((ResponseBuilder) Response.ok().entity(response)).type("application/json").build();

    } catch(Exception E) {
        //error
    }
}

Project A response object container:

public class ServiceResponse<T> {

    private T response;

    public T getResponse() {
        return this.response;
    }

    public void setResponse(T response) {
         this.response = response;
    }

}

The interesting part, Project B:

public void callService() {

    //....HTTP request...

    //json object
    JSONObject json = new JSONObject(jsonResponse);

    //ServiceResponseEquivalent is the same as the ServiceResponse object of *Project A*
    decodeResponse(json, ServiceResponseEquivalent.class, ExamplePOJO.class);

}


//this is a recursive function
public <T, V> T void decodeResponse(JSONObject json, Class<?> responseModel, Class<V> responseObjectModel) {

    //this is the same as the ServiceResponse object of *Project A*
    Object reflectedInstance = responseModel.newInstance();

    //here I got the field "response" of ServiceResponse
    Field[] fields = reflectedInstance.getClass().getDeclaredFields();
    for(Field field: fields) {

         //I got the json object based on the field name
         Object objectFromResponse = json.get(field.getName());

         if(objectFromResponse instanceof JSONObject) {

             //this is the "response" property of *ServiceResponse* which I know is an instance of *ExamplePOJO* class (because who calls this function pass *Class<V> responseObjectModel*
             if(if(field.getName().equals("response")) {

                  //recursive call
                  objectFromResponse = decodeResponse(json.getJSONObject(field.getName()), responseObjectModel, responseObjectModel);
             } 
             //here I found another object inside the "response" object but I don't know which class is it. In this case it's an instance of *AnotherPOJO*
             else {

                 //I try to get the class from the name of the property: in order to work, the property must be named as its class
                 String className = "com.example.packace." + field.getName().toUpperCase().charAt(0) + field.getName().substring(1, field.getName().length());

                //className = com.example.package.AnotherPOJO                       
                //recursive call
                objectFromResponse = decodeResponse(json.getJSONObject(field.getName()), Class.forName(className), responseObjectModel);

                //I try to set the object inside the response one
                //HERE IT FAILS
                BeanUtils.setProperty(reflectedInstance, field.getName(), objectFromResponse);

             }
             //here we found another Object but we don't know 
         } else {

             //I add the element
             BeanUtils.setProperty(reflectedInstance, field.getName(), objectFromResponse);
         }
    }

}

JSON example

The client receive this JSON:

{
    "response": { //response is an instance of ExamplePOJO
        "id":"1",
        "anotherPOJO":{
             [...]
        }
    },
    [ ...other fields...]
 }

The problem

When the decodeResponse tries to decode the AnotherPOJO object inside the recursive call throws this exeption:

java.lang.IllegalArgumentException: Cannot invoke com.example.package.ExamplePOJO.setAnotherPOJO on bean class 'class com.example.pacjage.ExamplePOJO' - argument type mismatch - had objects of type "com.example.package.AnotherPOJO" but expected signature "com.example.package.AnotherPOJO"

As it's obvious from the exception, the objects are an instance of the same class.

Any ideas?


Which could be a better approach to decode objects of unknown class? This:

String className = "com.example.packace." + field.getName().toUpperCase().charAt(0) + field.getName().substring(1, field.getName().length());

 //className = com.example.package.AnotherPOJO                      
 //recursive call
 objectFromResponse = decodeResponse(json.getJSONObject(field.getName()), Class.forName(className), responseObjectModel);

has the obvious problem that the field must be named as its class.





Aucun commentaire:

Enregistrer un commentaire