0%

java | spring boot 利用反射获取属性值

这是我在某一个项目中的应用,在 spring boot 项目中利用反射获取 Bean 中的属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.lou.springboot;

import com.alibaba.fastjson2.JSON;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;

@SpringBootApplication
public class Application {

public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(Application.class, args);
Run run = configurableApplicationContext.getBean(Run.class);
run.proc();
}


}


@Data
class Persons {
private String name1;
private Integer age1;

private String name2;
private Integer age2;
}

@Service
class PersonService {
public void proc(String cppMsg) throws NoSuchFieldException, IllegalAccessException {
Persons person = JSON.parseObject(cppMsg, Persons.class);

Field field = person.getClass().getDeclaredField("name1");
field.setAccessible(true);
System.out.println(field.get(person));
}
}

@Component
class Run {

@Autowired
private PersonService personService;

public void proc() throws NoSuchFieldException, IllegalAccessException {
personService.proc("{\"age1\":12,\"name1\":\"Antony\",\"age2\":22,\"name2\":\"tony\"}");
}
}
请我喝杯咖啡吧~