I am refactoring some legacy code and have come across a problem which I'm sure has a elegant solution - but I can't quite get there.
Initially there were a load of classes which extended an abstract class BaseType. Each of these classes has a enum - XmlElementTag - with values specific to the class:
enum XmlElementTag {value1, value2, value3}
They each also have a method :
private XmlElementTag getTag(String s){
XmlElementTag ret = null;
try {
ret = XmlElementTag.valueOf(s);
} catch (Exception e) {
Log.e(this, s+" is not supported tag");
}
return ret;
}
Every class has this exact same getTag method, but obviously they are all referring to the XmlElementTag enum specific to the class they are in. So, I'd like to get rid of this code duplication if I can.
I thought that maybe I could use a marker interface to solve this problem, so created one as which each XmlElementTag enum now inherits and rewrote the getTag method and put it in the super class.
So I have this in each class:
private XmlElementTag implements GenericTag {value1, value2, value3};
And this in the BaseType superclass:
public interface GenericTag {}
protected GenericTag getTag(String tagName){
XmlElementTag tag = null;
try {
tag = XmlElementTag.valueOf(tagName);
} catch (Exception e) {
Log.e(this, tagName+" is not supported tag");
}
return tag;
}
But again this doesn't work as the BaseType super class doesn't know what XmlElementTag is; Java doesn't allow abstract class variables; and creating this element in the BaseType won't work, as the getTag code will always refer to this enum, rather than the one in the class which extends BaseType.
Can anyone point me in the correct direction?
I guess you could write a static generic helper method that did what getTag does. It would need to use reflection under the hood, and would most likely require you to pass the enumeration's Class object as a parameter.
But IMO, you shouldn't. The getTag() method is kind of wrong-headed. It is turning what is effectively bad input into a null. That's wrong from two perspectives:
null values are going to come back to bite you as NullPointerExceptions.So really, your application code should either catch and deal with the IllegalArgumentException that arises when the conversion goes wrong, or it should allow the exception to bubble up to the top where it can be reported as (for instance) an error parsing the input stream.
(I don't think that an enum can either extend or be extended, so I don't think your enums can inherit a generic version of this class.)
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