Casting an object to its original class

casting, java

Solution

What you are trying to do is called a dynamic invocation. The closest thing you can do is to use reflection.

Method method = getClass().getMethod("someHandlingMethod", obj.getClass());
method.invoke(this, obj);

Problem

To avoid having to do this: ``` if (obj instanceof Class) { someHandlingMethod((Class) obj); } else if (obj instanceof AnotherClass) { someHandlingMethod((AnotherClass) obj); } ``` Is it possible to automatically cast an Object to its known class as stated by `obj.getClass().getName()`? Second to that, is it neat and reliable? Or would it simply be better to use the "Chain of Responsibility" or "Handler" pattern? For context: The object received in my program is an object read from a ObjectInputStream transmitted over a network. All the objects received are of type 'Message', then I have several subclasses for types of message (such as AuthenticateRequest, ViewRequest). I want to handle these differently.

Original source