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);


    }

}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐