6

In JLS Sec 8.4.3.6, synchronized methods, it says:

class BumpTest {
    // ...
    static synchronized void classBump() {
        classCount++;
    }
}

has exactly the same effect as:

class BumpTest {
    // ...
    static void classBump() {
        try {
            synchronized (Class.forName("BumpTest")) {
                classCount++;
            }
        } catch (ClassNotFoundException e) {}
    }
}

This looks odd to me, not to mention over-complicated: why use Class.forName("BumpTest"), not BumpTest.class? It's not possible that BumpTest isn't loaded, because it's executing code from that class, after all. And writing it as it is, the checked ClassNotFoundException has to be caught and swallowed.

Is there a particular reason to write it in this way?

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • Maybe the example predates class literals. I'm not sure when class literals were introduced. – user2357112 Oct 31 '17 at 21:10
  • Basically, you're saying that if you just use with `BumpTest.class` instead of `Class.forName`? Have you tried it? Maybe their example is not the best one – Andrei Sfat Oct 31 '17 at 21:11
  • @user2357112 you are probably right: this example is in [the Java 1.0 spec](http://titanium.cs.berkeley.edu/doc/java-langspec-1.0/8.doc.html#55408), but there is no mention of class literals. If you add that as an answer, I'll accept. – Andy Turner Oct 31 '17 at 21:12

1 Answers1

3

It appears to just be a really, really old example, older than class literals. The same example appears in the JLS 1.0, before class literals were introduced.

user2357112
  • 260,549
  • 28
  • 431
  • 505