All Java classes in business logics we write, are objects of java.lang.Class. This means that EACH CLASS IS AN OBJECT OF Class, besides each can generate objects based on that class.

God Class: java.lang.Class; each other classes that creates objects are objects of this God Class.

Class source code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
java.lang.Class:

Private constructor. Only the JVM creates Class objects.
This constructor is not used and prevents the default
constructor being generated.
*/
private Class(ClassLoader loader, Class<?> arrayComponentType) {
// Initialize final field for classLoader. The initialization
// value of non-null prevents future JIT optimizations from
// assuming this final field is null
classLoader = loader;
componentType = arrayComponentType;
}

private constructor of class Class, meaning that it’s a private method. Comments also say that this method can only be invoked by JVM to create Class objects.

The following is wrong:

1
Class myClass = new Class();

Although we cannot directly new to create objects this God Class, objects can be created via other channels. It is also noticed that methods pertinent to reflection are defined in java.lang.Class.

1st step in Java reflect

Goals of reflect:

  1. member variables;
  2. member functions;

Java reflect is carried for these two purposes. But, before reflect, how to get Class objects? Suppose we define a User class.

3 ways to obtain Class objects:

  1. 直接调用User类中的隐含静态成员变量class, 这个过程说明class静态变量定义在每一个普通类中, 我们无需自行定义; 调用方式:

    1
    Class myClass = User.class;
  2. 有隐含的静态变量class, 就有隐含的getter方法, User类对象通过getter方法获取Class对象:

    1
    2
    User user = new User();
    Class myClass = user.getClass();
  3. 使用Class类的静态方法forName()获取Class对象, 这个方法接收类的路径,实现运行时动态加载。这个过程需要try...catch, 一边在找不到类的时候提供堆栈信息。调用方式:

    1
    Class myClass = Class.forName(class路径)