Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Class.forName("BumpTest"), not BumpTest.class?

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?

like image 685
Andy Turner Avatar asked Oct 31 '17 20:10

Andy Turner


1 Answers

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.

like image 119
user2357112 supports Monica Avatar answered Oct 21 '22 04:10

user2357112 supports Monica