Drop object to source class

To not do this:

if (obj instanceof Class) { someHandlingMethod((Class) obj); } else if (obj instanceof AnotherClass) { someHandlingMethod((AnotherClass) obj); } 

Is it possible to automatically pass an object to its known class, as indicated by obj.getClass().getName() ?

Secondly, neat and reliable? Or would it just be better to use the Responsibility Chain or Handler template?

For context:

The object received in my program is an object that is read from an ObjectInputStream transmitted over the network. All received objects are of type "Message", then I have several subclasses for message types (such as AuthenticateRequest, ViewRequest). I want to treat them differently.

+4
source share
3 answers

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

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

You can use the cast method, which has a class object:

 Class clazz = obj.getClass(); clazz.cast(obj); 

Another option: if you have access to someHandlingMethod , you can add a parameter of type Class and pass obj.getClass() .

 public void someHandlingMethod(...., Class clazz); public void someHandlingMethod(...., AnotherClass clazz); 

You do not need to use this option. This will simply allow you to call proofreading with overload.

+1
source

This is a job for the visitor template. It is all too well known that an explanation is needed here. See Gang of Four or Wikipedia.

+1
source

All Articles