当前位置:网站首页>利用反射实现一个管理对象信息的简单框架
利用反射实现一个管理对象信息的简单框架
2022-07-31 19:30:00 【热爱编程的小宇】
利用反射实现一个管理对象信息的简单框架
看实现的效果:
然后运行我们的代码,它能够按照我们配置文件声明的类和属性去创造对应的实例
更改配置文件的信息:
对应的结果:
实现步骤:
首先通过Class类的**getResourceAsStream()**方法去获取一个文件的输入流
Properties properties = new Properties();
InputStream resourceAsStream = MySpring.class.getResourceAsStream(PROPRETIES_PATH);
首先通过Properties类来加载文件中的信息——包含类的全限定名、属性值
properties.load(resourceAsStream);
String className = properties.getProperty("className");
Set<Object> keySet = properties.keySet();
利用反射去加载文件中指定的类,并取得实例
Class<?> loadClass = Class.forName(className);
Object o = loadClass.newInstance();
通过反射获取类中所有的属性,并进行赋值
Field[] fields = loadClass.getDeclaredFields();
Arrays.stream(fields).filter(field -> keySet.contains(field.getName())).forEach(field -> {
field.setAccessible(true);
try {
field.set(o, properties.getProperty(field.getName()));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
代码整合
我的Person类
package com.zky.pojo;
/** * @authoer:zky * @createDate:2022/7/30 * @description: */
public class Person {
private String name;
private String age;
private String address;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
", address='" + address + '\'' +
'}';
}
}
我的School类
package com.zky.pojo;
/** * @authoer:zky * @createDate:2022/7/30 * @description: */
public class School {
private String name;
private String level;
@Override
public String toString() {
return "School{" +
"name='" + name + '\'' +
", level='" + level + '\'' +
'}';
}
}
实现类
package com.zky.myframe;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
/** * @authoer:zky * @createDate:2022/7/30 * @description: */
public class MySpring {
public static final String PROPRETIES_PATH = "application.propreties";
public static void main(String[] args) throws Exception {
Object o = beanFactory();
System.out.println(o);
}
public static Object beanFactory() throws Exception {
//读取配置文件的信息
Properties properties = new Properties();
InputStream resourceAsStream = MySpring.class.getResourceAsStream(PROPRETIES_PATH);
properties.load(resourceAsStream);
String className = properties.getProperty("className");
//TODO 修改为自动获取属性信息
Set<Object> keySet = properties.keySet();
//利用反射加载对应的类
Class<?> loadClass = Class.forName(className);
Object o = loadClass.newInstance();
Field[] fields = loadClass.getDeclaredFields();
Arrays.stream(fields).filter(field -> keySet.contains(field.getName())).forEach(field -> {
field.setAccessible(true);
try {
field.set(o, properties.getProperty(field.getName()));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
return o;
}
}
待优化:
目前属性只支持String类型的属性,其它属性等我有空再写~ 感觉不是很好弄。
目前只能管理对象一个对象,多个对象有待实现
边栏推荐
- 高通cDSP简单编程例子(实现查询高通cDSP使用率、签名),RK3588 npu使用率查询
- MySQL---operator
- Given an ip address, how does the subnet mask calculate the network number (how to get the ip address and subnet mask)
- 【公开课预告】:超分辨率技术在视频画质增强领域的研究与应用
- 基于WPF重复造轮子,写一款数据库文档管理工具(一)
- BOW/DOM(上)
- Batch (batch size, full batch, mini batch, online learning), iterations and epochs in deep learning
- MySQL - single function
- 抖音根据关键词取视频列表 API
- 获取抖音视频详情 API
猜你喜欢
MySQL---operator
35 MySQL interview questions and diagrams, this is also easy to understand
PCB叠层设计
关注!海泰方圆加入《个人信息保护自律公约》
【论文精读】iNeRF
Basics of ResNet: Principles of Residual Blocks
Unity 之 音频类型和编码格式介绍
How can we improve the real yourself, become an excellent architect?
1161. Maximum Sum of Elements in Layer: Hierarchical Traversal Application Problems
Combinatorics Notes (6) Associative Algebra of Locally Finite Partially Ordered Sets, Möbius Inversion Formula
随机推荐
What's wrong with the sql syntax in my sql
Thymeleaf是什么?该如何使用。
PCB stackup design
Batch (batch size, full batch, mini batch, online learning), iterations and epochs in deep learning
Cache and Database Consistency Solutions
【AcWing】The 62nd Weekly Match 【2022.07.30】
How can we improve the real yourself, become an excellent architect?
统计UTF-8字符串中的字符函数
Istio介绍
Poker Game in C# -- Introduction and Code Implementation of Blackjack Rules
Huawei mobile phone one-click to open "maintenance mode" to hide all data and make mobile phone privacy more secure
返回一个零长度的数组或者空的集合,不要返回null
leetcode 665. Non-decreasing Array
2022年Android 面经总结(附含面试题 | 源码 | 面试资料)
MySQL---sort and pagination
The whole network is on the verge of triggering, and the all-round assistant for content distribution from media people - Rongmeibao
Verilog实现占空比为5/18的9分频
ojdbc8 "Recommended Collection"迁移学习——Domain Adaptation
全网一触即发,自媒体人的内容分发全能助手——融媒宝