4
java | spring boot 利用反射获取属性值
source link: https://benpaodewoniu.github.io/2023/01/08/java185/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
java | spring boot 利用反射获取属性值
这是我在某一个项目中的应用,在 spring boot
项目中利用反射获取 Bean
中的属性。
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\"}");
}
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK