jeudi 24 novembre 2016

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");
}

}

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 Class.forClass() we can dynamically run any class in runtime.but i have some question in other case regarding static block.

if i use Class.forClass("org.ahmed.Student") in main method, then its executing the static block of Student. but if i declare Student s in main method its doesn't executethe static block. i thought Class.forClass("ClassName") is same as Declaring class with a variable name.





Aucun commentaire:

Enregistrer un commentaire