i wrote a program that have four classes .one of these classes is Date :

class Date {
public Date(int year,int month,int day)
}

in other classes there are some method that one of they're input is Date for example

public void f(Account account ,Date date)

i want to write the method in one of the classes that return the last time that one of the method with Date as input
are called

public Date g (){
//the code
}

what shoud the code be?

Recommended Answers

All 6 Replies

If the goal is to get the number of times a method is called, then the best solution is to apply a profiler, such as jprof or jvmmonitor. There is even one which comes with Java called hprof which will fit your needs, though of them all JVMMonitor seems best. Using one of these would be a lot more flexible and useful than the function you describe.

That having been said, way to write what you want is to have a class variable such as a counter that increments whenever the function in question is called:

class Date {
    private static int fooCounter = 0;

    public Date(int year,int month,int day) {
    }

    public Date foo() {
        fooCounter++;
        // the rest of the function ...
    }

    public int getFooCallCount() {
        return fooCounter;
    }
}

However, if you want to see what the last call return was, you'd change it like so:

class Date {
    private static Date lastFoo = null;

    public Date(int year,int month,int day) {
    }

    public Date foo() {
        Date retval;
        // the rest of the function ...
        lastFoo = retval;

        return retval;
    }

    public Date getFooLastCall() {
        return lastFoo;
    }
}

That having been said, the real solution probably is to use the profiler tools already at hand.

and don't forget that calling the method that increases or returns the counter introduces a call to the class :)

YOu can use the jvisualvm profiler that comes as standard with the JDK - you'll find it in your JDK bin folder. It's really easy.

to Schol-R-LEA: I add what you said in my code but i want to write this part of code in other class(not in Date class)

public Date getFooLastCall() {
        return lastFoo;
    }

so it said "lastfoo cannot be resolved to a variable"
what should i do??

define a variable called lastFoo of type Date...
Logical, once you think of it.

What do you mean?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.