Search code examples
javaexceptionmiddleware

Throw Exception based on Exception class name


I am implementing an object oriented middleware in Java. When invoking a remote call, I will get a response String containing either a value description or an Exception description (Exception class name and message). How can I now throw the respective Exception in my client stub code, knowing only the class name (and the message)?


Solution

  • Alright, thanks to the Reflection hint I figured it out. The result looks like this:

    RuntimeException ex = (RuntimeException) Class.forName(exceptionName).getConstructor(String.class).newInstance(exceptionMessage);
    throw ex;
    

    exceptionName needs to be the Exception's fully qualified class name.