views:

62

answers:

2

Hi,

I'm a beginner programmer, and am wondering how to work around this issue. The problem I am trying to solve is keeping a tally of static method calls in my program using a java.util.Observer.

Clearly, my original post must have just confused people so I'll leave it more open-ended: can anyone suggest a way to keep a static method count on a class that extends Observable?

Thanks for looking

A: 

Static methods don't change state of objects. Classes that extend Observable use Observable to notify Observers of changes to state. It doesn't make sense to me to have a static method call hasChanged or notifyObservers, because it shouldn't have changed anything. The Observer's update method gets called with a reference to the changed object and a static method isn't associated with any instance of a class, so the whole idea doesn't make sense.

The Observable object calls the observer something like this (this isn't really the code):

notifyObservers(){
    for(Observer observer : observers){
       observer.update(this, null);
    }
}

Calling notifyObservers from a static method doesn't make sense. this has no meaning here.

Change your method to non-static if it must fit into this scheme.

Jonathon
A: 

Thanks for the response. It was helpful. I solved this by adding a static method to my class which extended Observer, so that it has two update methods:

public static void update(Method method)
{
    //update count here
}

@Override
public void update(Observable observable, Object obj) {
            //override code to handle observable's call to update

    }

Whenever I ran into a static method that I needed to keep a count of, I called MyClass.update() and passed a reference to the calling Method using Reflection API's getEnclosingMethod().

ex:

MyObserver.update(new Object(){}.getClass().getEnclosingMethod());

Seems to work ok.

bizmark