获取Class类实例的4种方式

如下:其中forName方法在jdbc中加载Driver.class就用过 

public class Demo {
    public static void main(String[] args) {
        //方式一  调用运行时类的属性 .class
        Class c=  Demo.class;
        //方式二  调用运行时类的对象,调用getClass()方法
        Demo demo=new Demo();
        Class c2=demo.getClass();
        //方式三   调用Class的静态方法:forName(String classPath)
        try {
            Class c3=Class.forName("类路径");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //方式四 使用类的加载器ClassLoader
        ClassLoader classLoader = Demo.class.getClassLoader();
        try {
            Class c4=classLoader.loadClass("类路径");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}
发布了242 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_41813208/article/details/103555754