BeanUtils setProperty 抛出一个 IllegalArgumentException

Ern*_*avo 3 java reflection apache-commons-beanutils

环境详情

我有三个项目:

  • 项目 A:一个 Java REST 服务应用程序
  • 项目 B:Java 客户端应用程序
  • 项目 C:一个简单的 POJO 列表

前两个项目有第三个作为依赖项。

数据流

项目 B项目 A发出HTTP请求,项目 A使用项目 C的模型对象将其转换为JSON进行回复。

项目 B使用JSONObject解码JSON响应,并尝试使用BeanUtils获取原始 POJO 对象。

代码示例

ExamplePOJO 类(项目 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 ;
    }

}
Run Code Online (Sandbox Code Playgroud)

项目 A示例端点:

@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
    }
}
Run Code Online (Sandbox Code Playgroud)

项目 A响应对象容器:

public class ServiceResponse<T> {

    private T response;

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

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

}
Run Code Online (Sandbox Code Playgroud)

有趣的部分,项目 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);
         }
    }

}
Run Code Online (Sandbox Code Playgroud)

JSON 示例

客户端收到此JSON

{
    "response": { //response is an instance of ExamplePOJO
        "id":"1",
        "anotherPOJO":{
             [...]
        }
    },
    [ ...other fields...]
 }
Run Code Online (Sandbox Code Playgroud)

问题

decodeResponse试图解码AnotherPOJO递归调用内部对象抛出这个exeption:

java.lang.IllegalArgumentException:无法在 bean 类“class com.example.package.ExamplePOJO”上调用 com.example.package.ExamplePOJO.setAnotherPOJO - 参数类型不匹配 - 具有“com.example.package.AnotherPOJO”类型的对象,但预期签名“com.example.package.AnotherPOJO”

从异常中可以明显看出,对象是同一类的实例。

有任何想法吗?


哪个可能是解码未知类对象的更好方法?这个:

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);
Run Code Online (Sandbox Code Playgroud)

有一个明显的问题,即该字段必须被命名为它的类。

Ram*_*miz 5

这似乎是类加载问题。查看 的源代码Class.forName(String),它使用来自调用者的类加载器。这可能与加载您的 target 的类加载器不同responseModel,因此,请尝试以下操作:

//recursive call
objectFromResponse = decodeResponse(
    json.getJSONObject(field.getName()),
    Class.forName(className, true, responseModel.getClassLoader()),
    responseObjectModel);
Run Code Online (Sandbox Code Playgroud)

这应该确保模型子层次结构类由相同的类加载器加载。