The problems with this are:

1. I don't want a single converter object to convert more than one thing. Each converter should convert exactly one thing.

2. Your code doesn't take into account the fact that Foo may be derived from Bar (and therefore might call the method you're not expecting).

- Paul


On Nov 28, 2007, at 3:12 PM, Kevin Conaway wrote:

You could do it via reflection:

import java.lang.reflect.*;
public class ConverterService {

    public void convert(Object o) throws Exception{

        for (Method m : getClass().getDeclaredMethods()) {
            if (m.getName().equals("handle")) {
                Class<?> paramType = m.getParameterTypes()[0];
                if (paramType.isInstance(o)) {
                    m.invoke(this, o);
                }
            }
        }

    }

    public void handle(Foo foo) {
        System.out.println("Converting foo");
    }

    public void handle(Bar bar) {
        System.out.println("Converting bar");
    }

    public void handle(Baz baz) {
        System.out.println("Converting baz");
    }

    public static void main(String [] args) throws Exception {
        ConverterService c = new ConverterService();

        c.convert(new Foo());
        c.convert(new Bar());
        c.convert(new Baz());
    }
}

class Foo { }

class Bar { }

class Baz { }

Reply via email to