简体   繁体   中英

JsonString to JavaObject at runtime

I am trying to convert JSON String to Java Object at runtime. Is it possible?

  String className = errorInfo.getClassName(); String methodName = errorInfo.getMethodName(); String requestMessage = errorInfo.getMessage(); String reference3 = errorInfo.getReference3(); try { Class claz = Class.forName(className); Object obj = claz.newInstance(); Class[] parameterTypes = new Class[1]; parameterTypes[0] = Class.forName(reference3).getClass(); Method method = claz.getMethod(methodName, parameterTypes); method.invoke(obj, new ObjectMapper().readValue(requestMessage,<I have to pass here .class reference>>)); } catch(Exception ex) { } 

I was making basic mistake. Following code worked for me:

    String className = errorInfo.getClassName();
    String methodName = errorInfo.getMethodName();
    String requestMessage = errorInfo.getMessage();
    String reference3 = errorInfo.getReference3();

    try {
        Class<?> claz = Class.forName(className);
        Object obj = claz.newInstance();
        Class[] parameterTypes = new Class[1];
        Class<?> parameter = Class.forName(reference3);
        parameterTypes[0] = parameter;
        Method method = claz.getMethod(methodName, parameterTypes);
        method.invoke(obj, new 
        ObjectMapper().readValue(requestMessage,parameter));

    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM