Originally posted by srinivas bolloju:
taking this topic a little further ...
Q1) static block,is the one which is executed first when you run a program,why static initialiser block cannot contain any coderanch,private or protected var's?
Q2) when a var is declared&initialised in static block it is not available to other parts of the class, so in this case static is acting like a normal method,in sense ,vars dec&ini inside it is local to that.am i right? see sample program below
Q3)this is out of this topic, is there any way to display the accessmodifier and var type of a variable ?any methods declared for this in Object or any class ?
Q4)static ini block gets executed first when a program is run, is this the same case when a static variable is declared&initialised ,i.e,does the jvm first see for static var's declared in the class ?
Srinivas,
Here are the answers to your questions:
Q1) Static initializer blocks CAN "contain" (refer to) coderanch,private or protected vars of the class itself. However:
* If specified unqualified (e.g. v = 5) then they have to be static ones; instance variables need an object to be invoked on, and because a static initializer is, well..., static, there is no 'this' reference available.
* They have to be declared before the static initializer; otherwise you'll get a forward reference error by the compiler.
Q2) If I understand the question correctly, the answer is yes.
Q3) It can be done using reflection. Here is a
sample program. Assume that we are talking about a field named f in a class named C, where the class C lies in the same package as the Tester class which contains our little
test:
Compiling, running, and fixing possible bugs owing to oversight is left as an exercise to the reader.
Q4) The answer is yes. Says JLS 12.4 (
Initialization of Classes and Interfaces):
"Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class".
Hope this helps,
Panagiotis.