I have two hierarchies of parallel classes, and I would like to convert objects from one to another. I can do this by manually specifying which transformation to do, but I need to specify the transformation twice: first, when the actual conversion occurs, and second, when I need to call it. Is there a way to specify it only once?
So here is an example that works, but I would like to simplify. There are two conversion functions that let me go between the input classes (bI, cI) and the output classes (bO, cO). It's unavoidable. The instance of comparisons bothers 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 {}
private static aO convert(bI iVar) {return new bO();}
private static aO convert(cI iVar) {return new cO();}
public static void main(String argv []) {
final aI iVar = new bI();
final aO temp;
if(iVar instanceof bI) {
temp = convert((bI)iVar);
} else if (iVar instanceof cI) {
temp = convert((cI)iVar);
}
}
}
I would like to do something like this:
final a0 temp = convert(iVar.getClass().cast(iVar));
, . , , ?
final a0 temp = convertHelp({bI,cI}, iVar);
, convertHelp. . ?
.