Dynamic casting in Java
<p>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?</p>

<p>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?</p>

<pre><code>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);
        }
    }
}
</code></pre>

<p>I would like to do something like that:</p>

<pre><code>final a0 temp = convert(iVar.getClass().cast(iVar));
</code></pre>

<p>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?</p>

<pre><code>final a0 temp = convertHelp({bI,cI}, iVar);
</code></pre>

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

<p>Thanks.</p>
