I’m trying to dynamically add an attribute to some class from javalang:
JavaScript
x
5
1
In [1]: import javalang
2
In [2]: tree = javalang.parse.parse("class A { B c = ddd.doSomething(); }")
3
In [3]: print(tree.types[0].body[0].declarators[0].initializer)
4
MethodInvocation(arguments=[], member=doSomething, postfix_operators=[], prefix_operators=[], qualifier=ddd, selectors=[], type_arguments=None)
5
But when I try to simply assign a new attribute (qualifier_type
)
JavaScript
1
2
1
In [4]: tree.types[0].body[0].declarators[0].initializer.qualifier_type = "DDD"
2
Nothing happens:
JavaScript
1
3
1
In [5]: print(tree.types[0].body[0].declarators[0].initializer)
2
MethodInvocation(arguments=[], member=doSomething, postfix_operators=[], prefix_operators=[], qualifier=ddd, selectors=[], type_arguments=None)
3
Advertisement
Answer
Apparently, my attribute was there all the time, it just wasn’t printed, since the __repr__
implementation iterated over self.attrs
.
JavaScript
1
6
1
In [1]: import javalang
2
In [2]: tree = javalang.parse.parse("class A { B c = ddd.doSomething(); }")
3
In [3]: tree.types[0].body[0].declarators[0].initializer.qualifier_type = "DDD"
4
In [4]: print(tree.types[0].body[0].declarators[0].initializer.qualifier_type)
5
DDD
6
Explicitly adding my attribute, I can now print my class (scroll to the right to see it)
JavaScript
1
4
1
In [5]: tree.types[0].body[0].declarators[0].initializer.attrs += ("qualifier_type",)
2
In [6]: print(tree.types[0].body[0].declarators[0].initializer)
3
MethodInvocation(arguments=[], member=doSomething, postfix_operators=[], prefix_operators=[], qualifier=ddd, qualifier_type=DDD, selectors=[], type_arguments=None)
4