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 { }

On Nov 28, 2007 4:31 PM, Jason Terhune <[EMAIL PROTECTED]> wrote:

> Paul J. Lucas <pauljlucas <at> mac.com> writes:
>
> > On Nov 26, 2007, at 2:33 AM, Jerome Louvel wrote:
> >
> > > Your suggestion regarding the map of ConverterService is
> > > interesting. However, how would you handle the reverse conversion
> > > (from Representation to Object) ?
> >
> > Also using a map.  For both conversion directions, you allow for the
> > possibility of subclasses, e.g.:
> >
> > public class ConverterServiceMap extends ConverterService {
> >      // ...
> >
> >      public Object toObject( Representation rep ) {
> >          for ( Class c = rep.getClass(); c != Object.class;
> >                c = c.getSuperclass() ) {
> >              final ConverterService cs = m_toObjMap.get( c );
> >              if ( cs != null )
> >                  return cs.toObject( rep );
> >          }
> >          return super.toObject( rep );
> >      }
> > }
>
> I haven't actually tried this, but couldn't you just overload the
> toObject()
> and toRepresentation() methods?  Doesn't Java do the work of choosing the
> method with the most specific argument?
>
> For example:
> public class ConverterService extends ConverterService {
>  public Foo toObject(FooRepresentation fr);
>
>  public FooRepresentation toRepresentation(Foo f);
> }
>
>

Reply via email to