stringtemplate4 icon indicating copy to clipboard operation
stringtemplate4 copied to clipboard

Use Class.getDeclaredField instead of Class.getField

Open victornoel opened this issue 2 years ago • 2 comments

Hi,

I encountered that issue with v3 but I believe the problem exists also in v4.

Basically in https://github.com/antlr/stringtemplate4/blob/9a439491acc5b17d191316c9b3a99ab7bd340477/src/org/stringtemplate/v4/misc/ObjectModelAdaptor.java#L150 you call Class.getField and then try to make it visible via Field.setAccessible, but this is incorrect by design as Class.getField only return public fields!

Instead you should be using Class.getDeclaredField.

In practice, it means that it is always impossible to access private fields from templates.

In v3, the issue was in ASTExpr but I guess this won't be fixed there? :)

victornoel avatar Jun 14 '22 15:06 victornoel

Hmm...good point. Looks like that won't get inherited fields though:

https://stackoverflow.com/questions/16966629/what-is-the-difference-between-getfields-and-getdeclaredfields-in-java-reflectio

parrt avatar Jun 18 '22 22:06 parrt

@parrt right, I didn't know that. It actually makes sense because diverse class in an object hierarchy can have the same private fields... and then it means that maybe it's actually a bad idea to rely on the private fields/methods of an object then?

victornoel avatar Jun 19 '22 18:06 victornoel