Java OOP Example 2: Executing a Static Block with Class.forName()

 // File 1: smo_1.java
public class smo_1 {
    static {
        System.out.println("I am static");
    }
    int my_add(int x, int y) {
        return x + y;
    }
}

 // File 2: smo_main.java
public class smo_main {
    public static void main(String[] args) throws Exception {
        Class.forName("smo_1");  // Loads smo_1 and executes its static block WITHOUT an object!
        int x = 5, y = 16;
        smo_1 obj1 = new smo_1();
        System.out.println(obj1.my_add(x, y));
    }
}

Output:

I am static
21

1. Overloaded Signatures of java.lang.Class.forName() 🔝

Method Signature Runs static { }? Behavior
Class.forName(String className) Yes (Immediately) Loads the class by its fully qualified name and runs its static block.
Class.forName(String name, boolean init, ClassLoader cl) Configurable (init) If init == false, loads the class without running static { } yet.

2. Running a Static Block Without Creating Any Object 🔝

Calling Class.forName("smo_1") by itself forces the JVM ClassLoader to load and initialize smo_1, executing static { System.out.println("I am static"); } without ever calling new smo_1():

public class StaticBlockWithoutObject {
    public static void main(String[] args) throws ClassNotFoundException {
         // Executes smo_1's static { ... } block without calling 'new smo_1()':
        Class<?> loaded = Class.forName("smo_1");
        System.out.println("Loaded class metadata: " + loaded.getSimpleName());
    }
}

Terminal Output:

I am static
Loaded class metadata: smo_1

3. Important Execution Order: Static Blocks Run Only Once! 🔝

A class's static { ... } block executes only once when the class is first initialized in memory. Whether Class.forName("smo_1") runs first or new smo_1() runs first, whichever statement touches smo_1 first triggers "I am static", and subsequent calls do not repeat it:

public class StaticBlockRunsOnce {
    public static void main(String[] args) throws Exception {
        System.out.println("1. Calling Class.forName("smo_1")...");
        Class.forName("smo_1");  // Triggers static block here (1st time smo_1 is initialized)

        System.out.println("2. Calling new smo_1()...");
        smo_1 obj1 = new smo_1();  // Does NOT re-run static block!
        System.out.println("Sum: " + obj1.my_add(5, 16));
    }
}

Terminal Output:

1. Calling Class.forName("smo_1")...
I am static
2. Calling new smo_1()...
Sum: 21

4. Loading a Class Without Running Its Static Block (initialize = false) 🔝

If you want to inspect a class's metadata without triggering its static initializer block yet, pass false as the second argument to the 3-parameter overload:

public class LazyLoadWithoutInit {
    public static void main(String[] args) throws Exception {
        ClassLoader loader = LazyLoadWithoutInit.class.getClassLoader();
         // initialize = false loads bytecode WITHOUT running static { ... } yet:
        Class<?> c = Class.forName("smo_1", false, loader);
        System.out.println("Class loaded with initialize=false (static block not run yet)");

         // First active use (newInstance) now triggers the static block:
        c.getDeclaredConstructor().newInstance();
    }
}

Terminal Output:

Class loaded with initialize=false (static block not run yet)
I am static

5. Instantiating smo_1 & Calling my_add() Dynamically via Reflection 🔝

Once Class.forName("smo_1") returns the Class<?> object, you can create an instance and invoke my_add(5, 16) dynamically even if the class name came from a configuration file:

import java.lang.reflect.Method;

public class DynamicMethodInvoke {
    public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("smo_1");
        Object instance = clazz.getDeclaredConstructor().newInstance();
        Method addMethod = clazz.getDeclaredMethod("my_add", int.class, int.class);
        Object result = addMethod.invoke(instance, 5, 16);
        System.out.println("Reflective my_add(5, 16) = " + result);
    }
}

Terminal Output:

I am static
Reflective my_add(5, 16) = 21

6. Comparison: Static Initializer Block vs Instance Initializer vs Constructor 🔝

Block Type Syntax How Many Times? When Executed
Static Initializer static { ... } Once per class When class is first initialized (forName or 1st use).
Instance Initializer { ... } Once per object Every time new is called, right before constructor body.
Constructor smo_1() { ... } Once per object Every time new smo_1() is called.

7. Catching Checked ClassNotFoundException Safely 🔝

Because the string passed to Class.forName(...) is only resolved at runtime, the compiler requires either declaring throws Exception / throws ClassNotFoundException or wrapping the call in a try-catch block:

public class SafeForNameLoader {
    public static void main(String[] args) {
        try {
            Class.forName("com.plus2net.NonExistentPlugin");
        } catch (ClassNotFoundException e) {
            System.out.println("Caught ClassNotFoundException: " + e.getMessage());
        }
    }
}

Terminal Output:

Caught ClassNotFoundException: com.plus2net.NonExistentPlugin

8. Common Developer Pitfalls & Traps 🔝

Omitting the Package Prefix in Class.forName("Pack1.smo_1")

Class.forName() always requires the fully qualified class name! If smo_1 has package Pack1; at the top of its file, calling Class.forName("smo_1") throws a ClassNotFoundException—even if smo_main is in the exact same package! You must pass Class.forName("Pack1.smo_1").

ExceptionInInitializerError Inside a Static Block

If an uncaught runtime exception occurs inside static { ... } during Class.forName(), the JVM wraps it in an ExceptionInInitializerError and marks the class as permanently unusable for the rest of the program run.

9. Complete Compilable Java Program 🔝

public class OopExample2FullDemo {
    static int initCount = 0;
    static { initCount++; }
    public static void main(String[] args) throws Exception {
        Class.forName("OopExample2FullDemo");
        Class.forName("OopExample2FullDemo");
        if (initCount == 1) {
            System.out.println("All Java Class.forName() & static block checks passed! initCount=1");
        }
    }
}

Terminal Output:

All Java Class.forName() & static block checks passed! initCount=1

10. Frequently Asked Questions (FAQ) 🔝

Why is Class.forName("com.mysql.cj.jdbc.Driver") used in JDBC database code?

MySQL's JDBC driver class contains a static { DriverManager.registerDriver(new Driver()); } block. Calling Class.forName() executes that static block to register the driver (see Java MySQL Connection Tutorial).

What is the difference between Class.forName("smo_1") and smo_1.class?

Class.forName("smo_1") resolves a runtime String name and immediately runs the static block, whereas the class literal smo_1.class is checked at compile time and does not trigger the static block until a static member or constructor is accessed.

Can a class have multiple static { ... } blocks?

Yes. If a class defines several static blocks, the Java compiler merges and executes them in top-to-bottom source file order when the class is initialized.

Why was Class.newInstance() deprecated in Java 9+?

clazz.newInstance() bypassed checked exception checking. Modern Java uses clazz.getDeclaredConstructor().newInstance() instead.

Can a static block access non-static instance variables like int i?

No, not directly, because no object instance exists when the static block runs. It can only access static fields or instantiate an object inside the block first.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer