Question

Is there any way to override the default accessor for a property of an object in Java?

For example if I call Foo.bar, is there some way to know when the bar property is accessed without using a getter function?

Was it helpful?

Solution

What do you mean by, "without using a getter function"? If you extend Foo and override bar's getter method, and if bar is private, then yes you can find out when it is accessed.

This is one reason why properties should all be private, so that you the programmer have full control over what is seen, by whom, and what can change.

OTHER TIPS

No. Foo should be written like this:

private [type] bar;
public [type] getBar() { return bar; }

This allows you to do things when bar is accessed. If bar is public, then you're out of luck.

If I understand your question,

For example if I call Foo.bar, is there some way to know when the bar property is accessed without using a getter function?

Think about this question. A getter will allow you to add this functionality. If the property is private, this problem goes away as any caller is required to use the appropriate getter call. This is an entrenched Java Bean standard.

It's possible to weave aspects into your code to intercept field access, using Aspect Oriented programming (AOP: AspectJ, for example), however there are caveats to this solution which is beyond the scope of your question, but happy to answer in another one :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top