mercredi 31 mai 2017

Executing Method/Code based on run-time object type

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 needed to be done 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");
    }
}

class C extends A{
    void op(){
        System.out.println("c");
    }
}

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

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

    public static void main (String[] args) throws java.lang.Exception
    {
        List<A> l = someMethodThatGivesMeTheList();
        for(A a: l){
            print(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.

Aucun commentaire:

Enregistrer un commentaire