3

I have two parallel class hierarchies and I would like to convert objects from one to another. I can do it by manually specifying what conversion to do, but I need to specify the conversion twice: first when the actual conversion happens and second when I need to call it. Is there a way to specify it only once?

So here is the example, that works, but I would like to simplify. There are two convert functions that allow me to go between input classes (bI, cI) and output classes (bO, cO). This is unavoidable. The instanceof comparisons though bother me. Is there an elegant solution to avoid them?

public class ConversionTest {
    static public class aI {}
    static public class bI extends aI {}
    static public class cI extends aI {}

    static public class aO {}
    static public class bO extends aO {}
    static public class cO extends aO {}

    // Convert from bI to bO.
    private static aO convert(bI iVar) {return new bO();}
    // Convert from cI to cO.
    private static aO convert(cI iVar) {return new cO();}

    public static void main(String argv []) {
        // Input variable.
        final aI iVar = new bI();
        // Output variable.
        final aO temp;
        // Perform conversion.
        if(iVar instanceof bI) {
            temp = convert((bI)iVar);
        } else if (iVar instanceof cI) {
            temp = convert((cI)iVar);
        }
    }
}

I would like to do something like that:

final a0 temp = convert(iVar.getClass().cast(iVar));

But in this case, compiler complains that it can not find the proper convert function. Maybe I can specify an array of all possible conversions to try?

final a0 temp = convertHelp({bI,cI}, iVar);

I am not sure how I should implement this convertHelp function. It would iterate through the array and try to find the proper casting. Any suggestions?

Thanks.

1
  • I intentionally do not want input and output classes to be aware of each other. I agree with everyone who suggested that using polymorphism would do the trick, but I am looking for an alternative solution. In my case, I have no control over input/output classes and I can not extend them.
    – sjcomp
    Aug 5, 2010 at 13:03

6 Answers 6

3

Do you have access to the class implementations themselves? You could use polymorphism to make the conversion do the right thing if you stick it inside each class.

class ai
{
    public ao convert()
    {
        return new ao();
    }
}

class bi extends ai
{
    @Override
    public ao convert()
    {
        return new bo();
    }
}

class ci extends ai
{
    @Override
    public ao convert()
    {
        return new co();
    }
}

public static void main(String argv []) {      
// Input variable.      
final aI iVar = new bI();      
// Output variable.      
final aO temp = iVar.convert();
}
1
  • Exactly. Note that (since Java 5) you can use a covariant return type when overriding (i.e. @Override public co convert() { return new co(); } ).
    – meriton
    Aug 4, 2010 at 20:24
1

Given that you can't modify the input/output classes, the cleanest solution may be to use reflection:

class Converter { 
   public ao convert(ai iObj) {
      final Method m = getClass().getDeclaredMethod("cvrt", iObj.getClass());
      return (ao)m.invoke(this, iObj); 
   }

   public ao cvrt(ai iObj) {
      return new ao();
   }

   public bo cvrt(bi iObj) {
      return new bo();
   }

   public co cvrt(ci iObj) {
      return new co();
   }
}
1
  • I was looking for something which could provide me with a better type safety, but if anything I like this solution better than manual specification.
    – sjcomp
    Aug 5, 2010 at 20:00
1

The implementation you already have is correct, and it's much prettier than what you'd get using the reflection APIs.

You can implement ConvertHelp; it would need to take an array of Class objects as parameter. But, again, the body of ConvertHelp would be very ugly.

What you are doing is against the ideals of a statically typed language. Java is not designed to make it easy - it's very easy to produce unsafe code this way.

1
  • I tried to use Class object, but could not get it to work. I just do not know what should be the input type for the list of classes. Maybe I need to use raw class, instead of generics.
    – sjcomp
    Aug 5, 2010 at 13:01
0
private static aO convert(aI iVar) {
  if (iVar instanceof bI)
    return new bO();
  if (iVar instanceof cI)
    return new cO();
  return new aO();
}
2
  • :) I am trying to avoid instanceof, because I have a lot of classes.
    – sjcomp
    Aug 5, 2010 at 13:05
  • What does that have to do with anything? Aug 23, 2010 at 11:44
0

If you don't want your input classes to be dependent on the output classes, you can still benefit from polymorphism:

interface IFactory<T> {
   public T createA();
   public T createB();
   public T createC();
}

class ai
{
    public T convert(IFactory<T> f)
    {
        return f.createA();
    }
}

class bi extends ai
{
   @Override
   public T convert(IFactory<T> f)
   {
       return f.createB();
   }
}

class ci extends ai
{
   @Override
   public T convert(IFactory<T> f)
   {
       return f.createB();
   }
}

class FactoryO extends IFactory<ao> {
   public ao createA() {
      return new ao();
   }

   public bo createB() {
      return new bo();
   }

   public co createC() {
      return new co();
   }
}

To perform the conversion:

FactoryO f = new FactoryO();
ai ivar = // ...
ao ovar = ivar.convert(f);
0
0

Ideally, as suggested by the other posters, you should have a convert method on the input classes so that they can yield the output classes by themselves. If you want to have a parallel hierarchy of converters, your best recourse is to use the Visitor pattern.

You can define a ConverterVisitor interface and have two implementations as follows:

static public interface ConverterVisitor {
  public aO convert(aI iVar);
}

static public class bIConverter implements ConverterVisitor{
  public aO convert(aI iVar){
  // requires a cast from aI to bI
    return new bO();
  }
}

static public class cIConverter implements ConverterVisitor{
  public aO convert(aI iVar){
    // requires a cast from aI to cI
    return new cO();
  }
}

But the bI and cI classes need to be modifiable as well which is not what you want to do.

Hence the only solution that remains is to use a ReflectionVisitor pattern.

This would involve writing a class that would fetch the corresponding converter using some kind of naming convention. In this case the converter's name is obtained using the convention of appending "Converter" to the class name. So a converter factory implementation may look like this:

static public class ConverterFactory {

public aO convert(aI ai) throws Exception {
  return (aO) ((ConverterVisitor) Class.forName(ai.getClass().getName() + "Converter").newInstance()).convert(ai);
  }
}

Very ugly! but it works!

The second alternative is to use some kind of registry in your factory. Here is full listing. This is better since it uses generics to avoid multiple casts.

import java.util.HashMap;
import java.util.Map;

public class Trial {
        static public class aI {}
        static public class bI extends aI {}
        static public class cI extends aI {}

        static public class aO {}
        static public class bO extends aO {}
        static public class cO extends aO {}

        static public interface ConverterVisitor<T extends aI> {
            public aO convert(T iVar);
        }

        static public class bIConverter implements ConverterVisitor<bI>{

          public bIConverter(ConverterFactory converterFactory){
              converterFactory.register(bI.class, this);
          }

          public aO convert(bI iVar){
              return new bO();
          }
        }

        static public class cIConverter implements ConverterVisitor<cI>{

              public cIConverter(ConverterFactory converterFactory){
                  converterFactory.register(cI.class, this);
              }


             public aO convert(cI iVar){
                  return new cO();
             }
         }


        static public class ConverterFactory {
            public Map<Class<?>,ConverterVisitor<?>>converterRegistry = new HashMap<Class<?>, ConverterVisitor<?>>();

            public <T extends aI> void register(Class<T> clazz,ConverterVisitor<T> converter){
                converterRegistry.put(clazz,converter);
            }

            @SuppressWarnings("unchecked")
            public<T extends aI> aO convert(T ai) {
                return ((ConverterVisitor<T>)converterRegistry.get(ai.getClass())).convert(ai);
            }
        }


        public static void main(String argv []) throws Exception {
            // Input variable.
            final aI iVar = new bI();
            // Output variable.
            aO temp = null;
            // the three lines below must be done in some generic place within the program. 
            ConverterFactory factory = new ConverterFactory();
            new bIConverter(factory);
            new cIConverter(factory);

            temp = factory.convert(iVar);
            System.out.println(temp);
        }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.