I have the below objects
interface Adapter<T> {
T fromXml(XML xml);
XML toXml(T obj); //ignoring this in implementations
}
abstract class AbstractAdapter<T> implements Adapter<T>{
T fromXml(XML xml) { //template method
validate(xml);
return parse(xml);
}
abstract void validate(Xml xml);
abstract T parse(Xml xml);
}
class MyObjectAdapter extends AbstractAdapter<MyObject> {
MyObject parse(XMl xml) {return null;}
void validate(Xml xml) {}
}
class AnotherObjectAdapter extends AbstractAdapter<AnotherObject> {
AnotherObject parse(XMl xml) {return null;}
void validate(Xml xml) {}
}
class AdapterFactory {
Adapter<?> createAdapter(String objectType) {
if (objectType == "MyObject") return new MyObjectAdapter();
if (objectType == "AnotherObject") return new AnotherObjectAdapter();
}
public static void main(String args[]) {
AdapterFactory factory = new AdapterFactory();
//********
Adapter<MyObject> myobjectAdapter = (Adapater<MyObject>) factory.createAdapter("MyObject");
MyObject obj = myobjectAdapter.fromXml(getXml(args));
}
How do I avoid the downcasting I do in the line marked ** above?
The objects that need to have an adapter do not have any relation between them, they are generic data objects.
You have an class name in a
Stringand you’re trying to go from that to the actual type. That is always going to involve a cast. If you remove theAdapterFactoryand hence theString, then there is no problem.(Usual note that
==onStrings isn’t typically what you want.)