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)
{
}

2
  • Please check this post and this post to actually understand how to load the class into JVM and then using the Jackson as you are using to convent it. Commented May 9, 2018 at 12:14
  • @Hearen : Thanks for the help. I will go through it. Commented May 9, 2018 at 12:23

1 Answer 1

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();
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.