Ahmed Raaj Ahmed Raaj - 1 year ago 117
Java Question

java class.forClass() vs Class declaration

I have one class Student which is

package org.ahmed;

public class Student {

public Student() {
// TODO Auto-generated constructor stub
System.out.println("Generated constructor");

static { // static block
System.out.println("Hello world static");

{ // insance block
System.out.println("Hello world non static");

and then

public class Main {

public static void main(String[] args) throws ClassNotFoundException {
Class.forName("org.ahmed.Student"); // this line causing static block execution in Student class
// Student s; // this line doesn't execute the static block.

I understand by using
we can dynamically run any
class in runtime. But I have some question in other case regarding
static block.

If I use
in my
method, then it's
executing the static block of
. But if I declare
Student s
method its doesn't execute the static block. I thought
is same as declaring class with a variable

Answer Source

From javadoc:

Invoking Class.forName(className) method is equivalent to: Class.forName(className, true, currentLoader), where the second parameter specifies whether or not the class will be initialized.

So if you don't want to initialize the class, just call the method with initialize = false, e.g:

Class.forName("org.ahmed.Student", false, this.getClass().getClassLoader())}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download