Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting an object to its original class

Tags:

java

casting

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.

like image 343
Chris Watts Avatar asked Apr 28 '13 20:04

Chris Watts


1 Answers

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);
like image 98
Peter Lawrey Avatar answered Sep 30 '22 05:09

Peter Lawrey