how do I interpose on Long/String compareTo()?

279 Views Asked by At

I have a class implementing a data structure storing Comparable objects. Some instances hold Longs and other Strings.

I want to count the number of comparisons that occur, without changing the data structure class or the application too much.

One natural idea is to implement a new class (say MyLong) whose compareTo() increments some statistics counter and then calls the real compareTo(). Then change the app to store MyLongs instead of Longs, etc. This doesn't work because I can't inherit from Long or String.

Can this approach be made to work? Is there another way of accomplishing this goal?

3

There are 3 best solutions below

0
On BEST ANSWER

"prefer composition over inheritance"

Write a new class MyLong that implements Comparable (and probably extends Number) and contains a Long. Then have it pass all calls on to the contained Long, except the ones you want to instrument; for those it increments the counter and passes them to Long.

0
On

If the criteria of your project permits, your data structure could store objects which implement a Comparator interface. A custom comparator might allow you to count the total number of compares made with the given comparator. Just a thought.

0
On

You could do that fairly early with AspectJ.

You would basically write a pointcut around your compareTo method of the implementing class and add a counter there.