Reputation: 13
Working on a customised JSON Converter to comply with company standard (basically adding many tags and handling for enum). The converter only works for objects with a public nullary constructor, so it had some problem with those objects enhanced by Spring and it has to workaround by something like this:
((Advised) advised).getTargetSource().getTargetClass();
The final product works pretty well, but having Spring library imported makes it a bit too large and we decided to have 2 different classes, one for projects which are using Spring and the other for those aren't.
Ideally, the 2 Converters should look something like this:
JsonConverter.java
public class JsonConverter {
// public static toObject(){...}
// public static toJSON(){...}
// other methods
protected static resolveTargetClass(Object obj){return obj.getClass();}
}
SpringJsonConverter.java
public class SpringJsonConverter extends JsonConverter {
protected static resolveTargetClass(Object obj){
if(obj instanceof Advised)
((Advised) obj).getTargetSource().getTargetClass();
return obj.getClass();
}
}
And just as everyone knows, this won't work as resolveTargetClass
is static and not overridable. Is there any elegant way to do this? I would like to keep everything static as this converter had already been used by many projects and fixing it would cost so much time.
Upvotes: 1
Views: 127
Reputation: 140603
Seriously: don't use static here.
static leads to tight coupling between classes, and as you figured yourself: it "kills" polymorphism. In that sense: it is the opposite of good practices. Not always, but as soon as it hampers your ability to create a good design, static is obviously the wrong approach.
Thus: simply drop the static keyword from your current code. Yes, that will cost you now. But it enables you to do the right thing in the future.
Upvotes: 3