Open suoyi123wang opened 3 years ago
Is this really a bug in StringTemplate?
AttributeRenderer
classes like DateRenderer
are only ever invoked by StringTemplate if they were previously registered via STGroup.registerRenderer(Class<T>, AttributeRenderer<? super T>)
.
Obviously you will run into trouble if you do this:
DateRenderer dateRenderer = new DateRenderer();
group.registerRenderer(Object.class, dateRenderer);
But you shouldn't do that as it would cause ST to invoke DateRenderer
for any type extending Object
, e.g. Integer
or String
.
In my opinion, you should register DateRenderer
as shown below:
DateRenderer dateRenderer = new DateRenderer();
group.registerRenderer(Calendar.class, dateRenderer);
group.registerRenderer(Date.class, dateRenderer);
This way, StringTemplate will only ever use it on Calendar
and Date
instances.
That said, one could argue that StringTemplate should explicitly mention this in its Attribute Renderers docs.
Alternatively, StringTemplate could split up DateRenderer
into two classes, one implementing AttributeRenderer<Calendar>
, the other implementing AttributeRenderer<Date>
. That way, the compiler would reject the invalid registerRenderer()
call.
However, your proposed solution of changing the toString(...)
method to ignore any object which is neither a Date
nor a Calendar
would only hide the problem of having registered the DateRenderer
the wrong way.
I would welcome any update to the documentation from those with experience in this issue! :)
for this toString method in picture below
when the type of first parameter is not Calendar or Date, there will be ClassCastException; So when cast to Date, should add