Reputation: 376
I need some thing like a Python decorator. I need to store some information, specifically the method called, its start time, its end time, and its arguments. I cannot import anything outside of Java 1.5 libraries. Is there some thing like what is available in Python?
Upvotes: 4
Views: 10987
Reputation: 105053
@Loggable
annotation and an AspectJ aspect from jcabi-aspects may help you. Annotate all your methods and every time they are being called SLF4J will receive log messages:
@Loggable(Loggable.DEBUG)
public String load(URL url) {
return url.openConnection().getContent();
}
In the next versions of jcabi-aspects
a full logging of a class will be implemented: https://github.com/yegor256/jcabi/issues/129
Upvotes: 0
Reputation: 2027
You might get away with a Java Proxy
class if you can rely on interface methods only.
Upvotes: 0
Reputation: 12495
No, Python decorators do not let you monitor all the code without changing anything. You still have to put your decorator everywhere (and - essentially - wrap each of your functions into a function that does the counting).
I am not sure if I understand your requirements (you do not say if you need the code for production or testing; also, the requirement "not to import anything" is bizarre: are all your classes in the default package? are you allowed to use an IDE and a compiler?), but I think the simplest way would be to use Javassist (the second link kindly provided by cschooley is a perfect introduction), but do not use the agent: instead use CtClass#write() to instrument class files and save them to disk (possibly in a custom ant task). This way the final build will not need any special set-up.
Upvotes: 0
Reputation: 586
Java Instrumentation?
http://download.oracle.com/javase/6/docs/api/java/lang/instrument/Instrumentation.html
Example:
Upvotes: 2
Reputation: 31182
You can try some profiler using Java Management Extensions or java agent.
See http://java.sun.com/developer/technicalArticles/releases/j2se15/#mnm
Upvotes: 2