stringtemplate4 icon indicating copy to clipboard operation
stringtemplate4 copied to clipboard

Test failure: ClassCastException In DateRenderer

Open suoyi123wang opened this issue 2 years ago • 2 comments

for this toString method in picture below image

when the type of first parameter is not Calendar or Date, there will be ClassCastException; So when cast to Date, should add

if (value intanceof Date)

image-20211013125710012

suoyi123wang avatar Oct 15 '21 07:10 suoyi123wang

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.

bannmann avatar Oct 20 '21 21:10 bannmann

I would welcome any update to the documentation from those with experience in this issue! :)

parrt avatar Oct 29 '21 20:10 parrt