• Post Reply Bookmark Topic Watch Topic
  • New Topic

static block called before executing static method  RSS feed

 
Martin Lira
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gurus,
I have a Class Test:


When I invoke the Test.testStaticMethod() (from some different class) the static block is executed first before the testStaticMethod. My question is why does that happen? And can I avoid that.

Thanks,
Martin
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think that will always be the case.

TheClass.theMethod()

The JVM initializes TheClass before it calls theMethod. You wouldn't want it running methods on uninitialized classes! You have to be able to rely on static variables and such being ready before your method runs.

Hope that helps!
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could put testStaticMethod() in a superclass of Test and give the static initializer block access to variables in the superclass containg the results of running testStaticMethod().

Here's what's happening. The very first (in execution order) reference to a class causes the ClassLoader to read the .class file and set up some basic class structures like the bytecode and the static variables in memory. All static initializers, both static initializer blocks and initializers of static variables contained in type declarations, are then executed in the order they appear in the source program. Only then is the first statement referring to the class executed.

If the class has superclasses that have not already been loaded, they must be loaded before the class in question. However, any subclasses that have not yet been referenced are not yet loaded.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Martin Lira:

When I invoke the Test.testStaticMethod() (from some different class) the static block is executed first before the testStaticMethod. My question is why does that happen? And can I avoid that.


The whole point of a static initializer is that it is executed before any method is called. If you don't want that code to execute, you need to put it elsewhere.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I suspect that it doesn't run *every* time you call the static method. It *should* only run the first time you call it. Why don't you check this out?

Also, if this still isn't the behavior you want, you should describe what you are trying to do. I'm sure someone here will have some good suggestions for alternative ways to go about it.

Keep coding!

Layne
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!