反射

Java程序三阶段

image-20220121143040314

反射入门小demo

package com.jt.reflectionTest;

import com.sun.org.apache.xpath.internal.SourceTree;

import java.io.FileInputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Properties;

public class Reflection {
    public static void main(String[] args) throws Exception {
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\Name.properties"));

        //得到类路径
        String classfullpath = properties.get("classfullpath").toString();
        //得到要操作的方法
        String method = properties.get("method").toString();

        //根据路径,创建Cat 对象,类型为Class
        Class<?> cls = Class.forName(classfullpath);
        System.out.println("cls="+cls);
        //创建cat对象,类型为Cat , 就相当于根据类创建对象
        Object o = cls.newInstance();
        System.out.println("o的运行类型="+o.getClass());

        //根据路径 得到想要执行的方法对象。是类里的方法 用 Class类型的 cls点
        Method method1 = cls.getMethod(method);
        //执行方法
        System.out.println("******执行方法*********");
        method1.invoke(o);  //o对象的方法 就相当于 o.hi()
        System.out.println("******获得属性**********");
        //getField 不能得到私有属性
        Field nameField = cls.getField("name");
        System.out.println(nameField.get(o));//传统:对象.属性名  反射:成员变量对象.get(对象)
        //得到构造方法
        System.out.println("*******无参构造*********");
        Constructor<?> constructor = cls.getConstructor();//返回无参构造
        System.out.println(constructor);
        System.out.println("*******有参构造**********");
        Constructor<?> constructor1 = cls.getConstructor(String.class);
        System.out.println(constructor1);

    }
}

image-20220121160218157

输出结果:

image-20220121160206598

class类

image-20220121162327279

image-20220121163900732

image-20220121170021761

获取Class类对象

image-20220121172609741

image-20220121172733001

image-20220121172805979image-20220121172839679

image-20220121173106045

输出结果

image-20220121173146201

补充:

image-20220121173246552

哪些类有Class对象?

image-20220121173632182

案例:

image-20220121173920690

输出结果;

image-20220121174009946

类的加载过程:

image-20220121174820122

出结果;

[外链图片转存中…(img-aDBF9dQK-1646703872468)]

类的加载过程:

[外链图片转存中…(img-GTSW4Dhh-1646703872468)]

image-20220121174927373

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐