2
votes

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).

1
how do you write them in the file? is that text file? json or something? - Veselin Davidov
The writer will take specific (different depending on the type) fields from the bean and construct a byte representation from it, which is then saved as a text file. - Rossiar
Why does the writer need to downcast like this? It needs to access subclass fields? - Radiodef
ah you don't need all fields then. because beans by definition are serializeable so you can serialize them without carrying about the type. but it will store all fields - Veselin Davidov
It's not serializing the fields. They are manipulated before they are saved in the file. - Rossiar

1 Answers

2
votes

You could go with class-based generics rather than method-based:

public abstract class BeanWriter<T extends Bean> {
    public abstract boolean writeBean(T bean);
}

public class BeanAWriter extends BeanWriter<BeanA> {
    public boolean writeBean(BeanA bean) {
        bean.accessBeanAProperty();
    }
}