0

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)
{
}
Ram Pratap
  • 482
  • 4
  • 9
  • Please check this [post](https://stackoverflow.com/questions/1781091/java-how-to-load-class-stored-as-byte-into-the-jvm) and [this post](https://stackoverflow.com/questions/9832421/load-a-byte-array-into-a-memory-class-loader) to actually understand how to load the **class** into JVM and then using the [Jackson](http://www.baeldung.com/jackson-object-mapper-tutorial) as you are using to convent it. – Hearen May 09 '18 at 12:14
  • @Hearen : Thanks for the help. I will go through it. – Ram Pratap May 09 '18 at 12:23

1 Answers1

1

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();
    }
Ram Pratap
  • 482
  • 4
  • 9