I have encountered some code in a project at work where we have JavaBeans. I have discovered a Writer object that writes these beans to file. Unfortunately this uses instanceof to ask what type the bean is, before writing to file, like so:
if (bean instanceof BeanA) {
writer.handleBeanA(bean);
} else if (bean instanceof BeanB) {
writer.handleBeanB(bean);
} else if (bean instanceof BeanC) {
writer.handleBeanC(bean);
}
This is ugly and I want to replace it. So I took a look at splitting my writer into new classes Writer, BeanAWriter, BeanBWriter, BeanCWriter. I did this because obviously to keep my JavaBean structure I cannot add a method write() to the Beans.
When I call Writer, I pass my bean in as an abstract parent Bean, because the function calling this writer doesn't care what type of bean it is dealing with.
Now I go to write my new classes I encounter a problem, the function that I am overriding looks like this:
public abstract boolean <T extends Bean> writeBean(T bean);
but the code in BeanAWriter looks like this:
public abstract boolean <T extends Bean> writeBean(T bean) {
bean.accessBeanAProperty();
}
This code cannot work, because T is only recognised as a Bean and not as a BeanA, meaning that my instanceof is just replaced with a cast to BeanA...
Can anyone find a solution to this / what is going wrong here?
(I do not want to throw out the JavaBeans or hear about how it is an anti-pattern, as changing the beans could regress a lot of code).