spring boot反射方法应用总结.1.获取属性的值 2.返回具体方法 3.通过反射构造对象 4.获取注解 5.判断注解是否存在 6.通过反射设置对象的值

1.引入依赖

 <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
             <version>5.8.2</version>
        </dependency>

2.配置属性application.properties

demo.name=张三

3.测试

package com.example;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component(value = "test")
public class GirlFriend {
    //属性
    @Value("${demo.name}")
    private String name;

    //方法
    public String say() {
        return this.name + ": I 老虎油";
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

4.具体功能以代码演示

package com.example;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.ReflectUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
        GirlFriend bean = context.getBean(GirlFriend.class);

        //1.获取属性的值
        Object name = ReflectUtil.getFieldValue(bean, "name");
        System.out.println("获取属性的值,女朋友名称: " + name);

        //2.通过两个参数,1 类型的class, 2.方法名称
        //返回具体方法
        Method say = ReflectUtil.getMethodByName(GirlFriend.class, "say");
        Object value = ReflectUtil.invoke(bean, say);
        System.out.println("返回具体方法" + value);

        //3.通过反射构造对象
        GirlFriend girlFriend = ReflectUtil.newInstance(GirlFriend.class);
       
       //4.注解是否存在
        boolean b = AnnotationUtil.hasAnnotation(girlFriend.getClass(), Component.class);
        System.out.println(b);
        
        //5.获取注解
        Component annotation = AnnotationUtil.getAnnotation(girlFriend.getClass(), Component.class);
        System.out.println("注解的值:" + annotation.value());

        //6.通过反射设置对象的值
        ReflectUtil.setFieldValue(girlFriend, "name", "李老师");
        //获取属性的值
        Object name1 = ReflectUtil.getFieldValue(girlFriend, "name");
        //通过方法名获取方法的值
        Object say1 = ReflectUtil.invoke(girlFriend, "say");
        System.out.println("女朋友名称: " + name1);
        System.out.println(say1);


    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

great-sun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值