Open kjsmita6 opened 1 year ago
https://github.com/antlr/stringtemplate4/blob/master/doc/adaptors.md may be useful for you? Best of luck.
Here is a generic adaptor for records that I have used.
import org.stringtemplate.v4.Interpreter;
import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.misc.ObjectModelAdaptor;
import org.stringtemplate.v4.misc.STNoSuchPropertyException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.RecordComponent;
public class RecordAdaptor<R extends Record> extends ObjectModelAdaptor<R> {
public Object getProperty(Interpreter interpreter, ST self, R rtype, Object property, String propertyName)
throws STNoSuchPropertyException {
RecordComponent[] components = rtype.getClass().getRecordComponents();
for (RecordComponent component : components) {
if (component.getName().equals(propertyName)) {
try {
return component.getAccessor().invoke(rtype);
} catch (IllegalAccessException|InvocationTargetException e) {
throw new STNoSuchPropertyException(e, rtype, propertyName);
}
}
}
return super.getProperty(interpreter,self,rtype,property,propertyName);
}
}
Java 14 introduced the
record
keyword, which allows the creation of a lightweight "class" which really only holds data, similar to astruct
in C for example. StringTemplate does not support records because the way records define fields/method is different.Say I have a record
Person
(with the equivalent class after it) defined asThe record will have two methods,
name()
, andage()
, for getting the name and age fields.Related to #302, the fields of a record are private, and the methods do not follow StringTemplate's
findMember
method search pattern ofgetField
,isField
, andhasField
:The addition of a
tryGetMethod(clazz, memberName)
would solve this because the methods of a record are public. Or, fix the issue of #302, but doing this would help as well.