【学习笔记】反射学习笔记(还没看完,有空继续看)

反射

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值