开发者

Java - identify code which changes a class private member?

Using Eclipse or IntelliJ how can you locate all code that may modify a class' private member (type is Object)?

This member is available via a getter, so in theory a class could call getMyMemb开发者_开发问答er() and then set this to another value without calling the setter. Looking to find all possible cases of this..


This member is available via a getter, so in theory a class could call getMyMember() and then set this to another value without calling the setter.

I'm not sure I understand you correctly, but you can't change the reference returned by getMyMember() directly, just the object being referenced.


Rename the member; all accesses are now flagged as errors, allowing you to easily locate them.


In Eclipse, right-click on the private member and choose "Open Call Hierarchy."

Note that the private member is a reference, and cannot be modified outside the class -- with some exceptions like JNI and reflection.

Can you return a wrapper object from the getter?


You'll have to start with Java - identify code which changes a class private member? and then work through the list manually. To automate it, you'd have to generate a specific call-graph for those accesses. The call-graph isn't hard but they are generic for the whole abstract syntax tree, not limited to a specific member.

It might be faster to create a child class of the target member type and overriding whichever method is appropriate to log the access/modification, along with a stack trace, and then call the parent method. The getter can create the new class, pass in the real object in the constructor, and return the instrumented class. Something like an annotation or observer.


In Eclipse: Select the variable or private member, right click, references and workspace or use shortcut ctrl+shift+g on the variable


As mentioned above, the questions is partially flawed: a getObject() accessor will not allow code outside the class to mutate the state of the field.

If you have a setObject() mutator as well, and want to know through which code paths new values will "flow into" the field, try "Analyze..Dataflow to this" in IntelliJ.

See this IntelliJ blog post for more information: http://blogs.jetbrains.com/idea/2009/08/analyzing-dataflow-with-intellij-idea/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜