Search code examples
javaprimitive-typescomparetofunction-interposition

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


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?


Solution

  • "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.