Close

Java Reflection - Class.forName() Examples

Code Snippets Java Reflection Java Java API 


Class:

java.lang.Class

java.lang.Objectjava.lang.Objectjava.lang.Classjava.lang.Classjava.io.SerializableSerializablejava.lang.reflect.GenericDeclarationGenericDeclarationjava.lang.reflect.TypeTypejava.lang.reflect.AnnotatedElementAnnotatedElementLogicBig

Methods:

public static Class<?> forName(String className)
                        throws ClassNotFoundException

Returns the Class object associated with the class or interface with the given string name.



public static Class<?> forName(String name,
                               boolean initialize,
                               ClassLoader loader)
                        throws ClassNotFoundException

Returns the Class object associated with the class or interface with the given string name. The class is initialized only if the initialize parameter is true and if it has not been initialized earlier. Few lines from Section 12.4 of the Java Language Specification:

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
  • T is a class and an instance of T is created.
  • A static method declared by T is invoked.
  • A static field declared by T is assigned.
  • A static field declared by T is used and the field is not a constant variable (§4.12.4).
  • T is a top level class (§7.6) and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.
....

Examples


package com.logicbig.example;

public class TestClass {
private static int a = getAValue();

private static int getAValue() {
System.out.println("initializing");
return 5;
}
}

package com.logicbig.example;

public class MainClass {
public static void main(String[] args) throws Exception {
Class<?> aClass = Class.forName("com.logicbig.example.TestClass");
System.out.println(aClass);
}
}

Output

initializing
class com.logicbig.example.TestClass




In this example, TestClass will not be initialized.

package com.logicbig.example;

public class TestClass {
private static int a = getAValue();

private static int getAValue() {
System.out.println("initializing");
return 5;
}
}

package com.logicbig.example;

public class MainClass {
public static void main(String[] args) throws Exception {
Class<?> aClass = Class.forName("com.logicbig.example.TestClass", false,
MainClass.class.getClassLoader());
System.out.println(aClass);
}
}

Output

class com.logicbig.example.TestClass




See Also