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.
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();
}
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With