Class.forName()方法的作用

一、Class.forName()方法的源代码以及注释

    /**
     * Returns the {@code Class} object associated with the class or
     * interface with the given string name.  Invoking this method is
     * equivalent to:
     *
     * <blockquote>
     *  {@code Class.forName(className, true, currentLoader)}
     * </blockquote>
     *
     * where {@code currentLoader} denotes the defining class loader of
     * the current class.
     *
     * <p> For example, the following code fragment returns the
     * runtime {@code Class} descriptor for the class named
     * {@code java.lang.Thread}:
     *
     * <blockquote>
     *   {@code Class t = Class.forName("java.lang.Thread")}
     * </blockquote>
     * <p>
     * A call to {@code forName("X")} causes the class named
     * {@code X} to be initialized.
     *
     * @param      className   the fully qualified name of the desired class.
     * @return     the {@code Class} object for the class with the
     *             specified name.
     * @exception LinkageError if the linkage fails
     * @exception ExceptionInInitializerError if the initialization provoked
     *            by this method fails
     * @exception ClassNotFoundException if the class cannot be located
     */
    @CallerSensitive
    public static Class<?> forName(String className)
                throws ClassNotFoundException {
        Class<?> caller = Reflection.getCallerClass();
        return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
    }

二、方法的作用以及为什么使用

众所周知,java当中的任何一个类都是要装载在虚拟机上才能够运行,因此Class.forName()方法就是用来装载一个类的。
说的再通俗一点,就是要求jvm查找并且加载指定类,同时会执行指定类的静态代码段

三、理解代码

class A {
	public A() {  
		System.out.println("JiadeChen!");
	}
	
	public void show() {
		System.out.println("i like apples!");
	}
	
	static {
		System.out.println("Hello!");
	}
}

public class Main {
	
	public static void main(String[] args) throws Exception {
		A a = (A)Class.forName("main.A").newInstance();
		A aa = new A();
		aa.show();
		a.show();
	}
	
}

Class.newInstance():可以用来解耦合,其实就是将new()方法拆分成为了两步。第一步,首先调用class的加载方法加载指定的类,加载将会调用指定类的static代码段当中的代码;第二步,将指定类实例化。

发布了76 篇原创文章 · 获赞 18 · 访问量 2741

猜你喜欢

转载自blog.csdn.net/qq_43446165/article/details/104055771
今日推荐