• Java反射中Class.forName和classloader的区别


    Java中Class.forName和classloader都可以用来对类进行加载。

    Class.forName除了将类的.class文件加载到jvm中之外,还会对类进行解释,执行类中的static块。

    而classloader只干一件事情,就是将.class文件加载到jvm中,不会执行static中的内容,只有在newInstance才会去执行static块。

    Class.forName(name,initialize,loader)带参数也可控制是否加载static块。并且只有调用了newInstance()方法采用调用构造函数,创建类的对象。

    package com.yu.java.reflect;
    
    public class Line {
        static {
            System.out.println("static code executing: loading line...");
        }
    }
    package com.yu.java.reflect;
    
    public class Point {
        static {
            System.out.println("static code executing: loading point...");
        }
    }
    package com.yu.java.reflect;
    
    public class ClassLoaderAndForNameTest {
    
        public static void main(String[] args) {
            String wholeNameLine = "com.mangosoft.java.reflect.Line";
            String wholeNamePoint = "com.mangosoft.java.reflect.Point";
    
            System.out.println("classloader testing...");
            testClassLoader(wholeNameLine, wholeNamePoint);
            System.out.println("---------------------------------------");
            System.out.println("Class.forName testing...");
            testForName(wholeNameLine, wholeNamePoint);
        }
    
        //classloader
        public static void testClassLoader(String wholeNameLine, String wholeNamePoint) {
            ClassLoader loader = ClassLoader.getSystemClassLoader();
            Class<?> line;
            Class<?> point;
            try {
                line = loader.loadClass(wholeNameLine);
                point = loader.loadClass(wholeNamePoint);
                System.out.println("line " + line.getName());
                System.out.println("point " + point.getName());
            } catch (ClassNotFoundException e){
                e.printStackTrace();
            }
        }
    
        //Class.forName
        public static void testForName(String wholeNameLine, String wholeNamePoint) {
            try {
                Class line = Class.forName(wholeNameLine);
                Class point = Class.forName(wholeNamePoint);
                System.out.println("line " + line.getName());
                System.out.println("point " + point.getName());
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    运行结果如下:

  • 相关阅读:
    Python函数语法里的中括号和逗号是什么意思
    关于mysql配置文件中jdbc url 的记录
    MySQL 优化慢查询
    Windows10 解决端口占用问题
    数据结构与算法分析-表,栈,队列
    MySQL手动执行rollback,内部实现分析
    Docker 之 RabbitMQ安装教程 基于腾讯云
    Docker容器启动报WARNING: IPv4 forwarding is disabled. Networking will not work
    List按需转换Map
    位移运算符 1<<4
  • 原文地址:https://www.cnblogs.com/yuandluck/p/9476238.html
Copyright © 2020-2023  润新知