antlr / stringtemplate4

StringTemplate 4
http://www.stringtemplate.org
Other
943 stars 229 forks source link

Test failure: ClassCastException In DateRenderer #288

Open suoyi123wang opened 2 years ago

suoyi123wang commented 2 years ago

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

bannmann commented 2 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.

parrt commented 2 years ago

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