Executing Method/Code based on run-time object type

Viewed 169

I have this situation:

I have an abstract class, let's say A, implemented several times. In another part of the application, I have a list of A objects, and I have several operations that I need to do based on the actual type of the object in the list. As an example

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

abstract class A{
    abstract void op();
}

class B extends A{
    void op(){
        System.out.println("b");
    }
    void opB(){
        System.out.println("it's b again!");
    }
}

class C extends A{
    void op(){
        System.out.println("c");
    }
    void opC(){
        System.out.println("it's b again!");
    }
}

class Ideone
{
    public static void doStuff(B b){
        b.opB();
        //Some operation unique to class B
    }

    public static void doStuff(C c){
        //some operation unique to class C
        c.opC();
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        List<A> l = someMethodThatGivesMeTheList();
        for(A a: l){
            //Here it should use the right
            doStuff(a);
        }
    }
}

The example does not compile, but explains what I want to do. How?

I found only the possibility to apply a Visitor pattern, but that would require modifying class A and its subclasses to accept the visitor, and I would prefer to avoid it.

Using getClass() and switch\if is clumsy, not really what I'm looking for.

In the example I used two static methods, but some new classes, wrappers, everything can be used as long as it solves the problem, I have complete control over the code.

A similar question here is Calling method based on run-time type insead of compile-time type, but in my case I'm working with Java, so no dynamic type exists to solve my problem.

EDIT: I write here what I have written in the comments just to make it clearer. The operation cannot become a method of A because it represents things that must be separated, like GUI creation based on the actual type of data. A parallel hierarchy is possible as a wrapper, but still the need to create the right GUI object based on the actual object takes me back to this same problem, or at least so it seems to me.

EDIT 2 (the return): I have changed a little bit the example to better show that I need to do stuff based on the actual class. This is somehow farther from my case but the problem is the same, a collection erase the real object class and i need a way to recover it smarter that instanceof or getClass()

1 Answers
Related