trigger static init

R

Roedy Green

What is the canonical way to explicitly trigger a static class to load
and run thestatic init without actually invoking a real method?

you can't necessarily use newInstance since the class may not have
constructors.

Do you have to invent some dummy static method?
--
Roedy Green Canadian Mind Products
http://mindprod.com
When you were a child, if you did your own experiment
to see if it was better to put to cocoa into your cup first
or the hot milk first, then you likely have the programmer gene..
 
J

Jukka Lahtinen

Roedy Green said:
What is the canonical way to explicitly trigger a static class to load
and run thestatic init without actually invoking a real method?

I suggest Class.forName(String classname), if you just want to avoid
invoking a method of the class to be loaded and don't mind invoking
one of the Class class.

If you insist on not invoking any method of *any* class and thus don't
want to use Class.forName, you can refer to some public static attribute
of the class.
 
G

glen herrmannsfeldt

Roedy Green said:
What is the canonical way to explicitly trigger a static class to load
and run thestatic init without actually invoking a real method?
you can't necessarily use newInstance since the class may not
have constructors.

As far as I know, a class automatically has a no argument constructor,
even if you don't write one.

class myclass {
static int x;
}

compiles just fine, as does creating an object from it.
Do you have to invent some dummy static method?

Not that I know of.

-- glen
 
R

Roedy Green

As far as I know, a class automatically has a no argument constructor,
even if you don't write one.

You can't always do that. The sole explicit constructor may be private
to explicitly stop you from instantiating objects.
--
Roedy Green Canadian Mind Products
http://mindprod.com
When you were a child, if you did your own experiment
to see if it was better to put to cocoa into your cup first
or the hot milk first, then you likely have the programmer gene..
 
R

Roedy Green

, you can refer to some public static attribute
of the class.

But it had better not be a static final known at compile time, or it
will be optimised to a literal and referencing it won't load the
class.

I decided to handle it by putting in dummy public static void fireup()
methods that as a side effect load the class and run static init. If I
fail to call them, class loading is just procrastinated until first
use.
--
Roedy Green Canadian Mind Products
http://mindprod.com
When you were a child, if you did your own experiment
to see if it was better to put to cocoa into your cup first
or the hot milk first, then you likely have the programmer gene..
 
M

markspace

I decided to handle it by putting in dummy public static void fireup()
methods that as a side effect load the class and run static init. If I
fail to call them, class loading is just procrastinated until first
use.


This sort of idea sounds to me like the worst sort of hackish design
possible. Don't use statics for this use case. Use Factories, or
Strategies, or even just a Properties object if you only need to load a
few constants at runtime.
 
L

Lew

glen said:
As far as I know, a class automatically has a no argument constructor,
even if you don't write one.

class myclass {
static int x;
}

He meant no *accessible* constructors.

If the constructor is not accessible, its existence is moot.

And Java coding conventions call for type names to have an initial upper-case letter and be in camel case: 'MyClass'.
compiles just fine, as does creating an object from it.


Not that I know of.

The rules for class initialization are quite explicitly listed in the JLS, which document is eminently useful no matter how much one may affect to loathe it.
<http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.2>
 
L

Lew

Roedy said:
Jukka Lahtinen wrote, quoted or indirectly quoted someone who said :

But it had better not be a static final known at compile time, or it
will be optimised to a literal and referencing it won't load the
class.

I decided to handle it by putting in dummy public static void fireup()
methods that as a side effect load the class and run static init. If I
fail to call them, class loading is just procrastinated until first
use.

Two questions:

Why is it important to control when the class loads, instead of using the default?
What was wrong with 'Class#forName()', which is intended for the purpose and is not a hack?
 
L

Lew

Jukka said:
I suggest Class.forName(String classname), if you just want to avoid
invoking a method of the class to be loaded and don't mind invoking
one of the Class class.

If you insist on not invoking any method of *any* class and thus don't
want to use Class.forName, you can refer to some public static attribute
of the class.

Bear in mind that the 'class' literal does not apply here. Referencing the 'class' literal does not incur class initialization.
 
D

Daniel Pitts

What is the canonical way to explicitly trigger a static class to load
and run thestatic init without actually invoking a real method?

you can't necessarily use newInstance since the class may not have
constructors.

Do you have to invent some dummy static method?
If you have to worry about this problem, then you've got the wrong design.

Classes always have a constructor, but they may not have a Default
constructor, or the constructor may be private.

In any case, if you know about the class specifically before hand, then
you probably have the wrong design, and should convert it to a
non-static class. Probably you want dependency injection if you need
only one. Perhaps as a singleton if you *really* need that, but only as
a last resort.
 
A

Andreas Leitgeb

Lew said:
Referencing the 'class' literal does not incur class initialization.

from JLS 12.4.1:
A class [...] T is initialized immediately before first [...]
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used [ ... and not constant ... ]
T is a top-level class, and an assert statement (§14.10) lexically
nested within T is executed.

Does using a class-literal <T.class> in "synchronized(T.class) {...}" count
in for implicitly using the monitor-field of the Class<T>-instance, or is
it strictly undefined (or defined somewhere else)?

Btw., I don't understand the point about assert. If the assert is
lexically nested in T and gets executed, then I'd have naively thought,
that one of the first two points would necessarily have happened,
anyway, before the assert could be reached. What am I missing here?
 
J

Joshua Cranmer

Lew said:
Referencing the 'class' literal does not incur class initialization.

from JLS 12.4.1:
A class [...] T is initialized immediately before first [...]
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used [ ... and not constant ... ]
T is a top-level class, and an assert statement (§14.10) lexically
nested within T is executed.

Does using a class-literal<T.class> in "synchronized(T.class) {...}" count
in for implicitly using the monitor-field of the Class<T>-instance, or is
it strictly undefined (or defined somewhere else)?

So, the use of "T.class" creates an object of Class<T>, which is not
sufficient to cause T to be initialized. Some more inspection of the JLS
(and some experiments) leads me to the conclusion that a
synchronized(T.class) block can race with the initialization of T.

Experiments confirm that synchronized(T.class) does not cause
initialization of T.
 
A

Andreas Leitgeb

Joshua Cranmer said:
So, the use of "T.class" creates an object of Class<T>, which is not
sufficient to cause T to be initialized.

Thanks for hitting my nail of misconception right on its head :)
Some more inspection of the JLS
(and some experiments) leads me to the conclusion that a
synchronized(T.class) block can race with the initialization of T.
Experiments confirm that synchronized(T.class) does not cause
initialization of T.

Once I got creation of the Class<T> instance and initialization
of the class properly separated, then that is no longer a surprise :)

Thanks.
 
L

Lew

Lew said:
Referencing the 'class' literal does not incur class initialization.

from JLS 12.4.1:
A class [...] T is initialized immediately before first [...]
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used [ ... and not constant ... ]
T is a top-level class, and an assert statement (§14.10) lexically
nested within T is executed.

Does using a class-literal<T.class> in "synchronized(T.class) {...}" count
in for implicitly using the monitor-field of the Class<T>-instance, or is
it strictly undefined (or defined somewhere else)?

So, the use of "T.class" creates an object of Class<T>, which is not
sufficient to cause T to be initialized. Some more inspection of the JLS (and
some experiments) leads me to the conclusion that a synchronized(T.class)
block can race with the initialization of T.

Experiments confirm that synchronized(T.class) does not cause initialization
of T.

It used to, in contravention of the JLS.

"A class or interface will not be initialized under any other circumstance."
<http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.4.1>

It's important to note that the Java Language Specification explicitly forbids
class initialization from use of the 'class' literal. Prior to Java 5 there
was a bug that it did, which Sun fixed with version 5. This caused certain
libraries (notably Apache Commons) to break where they relied on the buggy
behavior, when run under Java 5+ under certain corner scenarios.
 
A

Andreas Leitgeb

Patricia Shanahan said:
Suppose S is a static class defined in T. I interpreted that as meaning
that executing an assert in S would trigger initialization of T.
Or suppose S is non-static, but the assert is in its static code.

I don't yet get it.

=== Main.java ===
public class Main {
public static void main(String[] args) {
Object foo = new Outer.Inner();
}
}
class Outer {
static {
System.out.println("Outer init");
}
public static class Inner {
static {
System.out.println("Inner init1");
assert 1==1 : "oups!";
System.out.println("Inner init2");
}
}
}
=== call ===
$ java -ea Other ;# ditto without the -ea
Inner init1
Inner init2
$ java -version
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) Server VM (build 20.1-b02, mixed mode)
$
=== end of SSCCE ===

So, it *is* possible to run code "lexically included in Outer"
without Outer having been initialized first (which I had wrongly
believed to be impossible), but assert itself doesn't seem to
have the specified effect. I also read §14.10, but that just
affirms, that (in order to determine the Assertion-flag for the
toplevel class "Outer") "Outer" would be initialized, too.
It doesn't seem to happen, though.
 
S

Steven Simpson

Suppose S is a static class defined in T. I interpreted that as meaning
that executing an assert in S would trigger initialization of T.

Or suppose S is non-static, but the assert is in its static code.

Can non-static S contain static code?
 
A

Andreas Leitgeb

Patricia Shanahan said:
Patricia Shanahan said:
On 4/11/2012 5:52 AM, Andreas Leitgeb wrote:
T is a top-level class, and an assert statement (§14.10) lexically
nested within T is executed.
[an example that shows this point wrong]
[another more elaborate example that shows this point wrong]

So, there seems to be a "bug", but no one seems to give a f^Hdime. ;-)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,701
Latest member
XavierQ83

Latest Threads

Top