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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With