zoukankan      html  css  js  c++  java
  • Class.forName调用时会加载对应类

    //20201224
    今天学习java类的反射机制的时候,讲到了forName()方法会加载类,在此记录一下细节

    forName调用时发生了什么

    • 会加载类,如果类中有静态代码块,则会执行其内代码,但不会执行无参构造内部代码
    • 举例(类代码&调用forName代码):
    //类
    package testPackage;
    
    public class User {
        static{
            System.out.println("User class has been load!");
        }
    
        public User(){
            System.out.println("constructor has been quote");
        }
    }
    /**
     * ===============================
     */
    public static void main(String[] args) throws Exception {
            FileReader fr = new FileReader("src/reflection/classinfo.properties");
            Properties pro =  new Properties();
            pro.load(fr);
            fr.close();
            String mm = pro.getProperty("className");
    //        System.out.println(mm);
            Class test = Class.forName(mm);
            User ss = new User();
        }
    
    • 配置文件内容(学习的时候顺便练了一下配置文件的读取)
    className=testPackage.User
    
    • 执行输出如下:

    img "执行输出"

    以上
    希望对大家有所帮助

  • 相关阅读:
    zoj 2876 Phone List
    zoj 2829 Beautiful Number
    zoj 2723 Semi-Prime(set)
    zoj 2835 Magic Square(set)
    zoj 2818 Root of the Problem
    zoj 2744 Palindromes
    zoj 1109 Language of FatMouse(map)
    zoj 2724 Windows Message Queue
    zoj 2722 Head-to-Head Match(两两比赛)
    zoj 2727 List the Books
  • 原文地址:https://www.cnblogs.com/lavender-pansy/p/14186155.html
Copyright © 2011-2022 走看看