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