当前位置:网站首页>利用反射实现一个管理对象信息的简单框架
利用反射实现一个管理对象信息的简单框架
2022-07-31 19:30:00 【热爱编程的小宇】
利用反射实现一个管理对象信息的简单框架
看实现的效果:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pF8lOM4l-1659182788166)(D:\note\笔记仓库\图片\image-20220730195726510.png)]](/img/55/2599a43429251b9f96097ec2be1679.png)
然后运行我们的代码,它能够按照我们配置文件声明的类和属性去创造对应的实例
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1dGinWU0-1659182788175)(D:\note\笔记仓库\图片\image-20220730195744424.png)]](/img/0e/bbb2d001e8166551c939bba113abb1.png)
更改配置文件的信息:![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qmaBKpw9-1659182788176)(D:\note\笔记仓库\图片\image-20220730200147432.png)]](/img/32/a53f95f839f07551814212c7782932.png)
对应的结果:
实现步骤:
首先通过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类型的属性,其它属性等我有空再写~ 感觉不是很好弄。
目前只能管理对象一个对象,多个对象有待实现
边栏推荐
- 保证接口数据安全的10种方式
- How to change npm to Taobao mirror [easy to understand]
- 财务盈利、偿债能力指标
- 关注!海泰方圆加入《个人信息保护自律公约》
- pytorch lstm时间序列预测问题踩坑「建议收藏」
- 迁移学习——Domain Adaptation
- Poker Game in C# -- Introduction and Code Implementation of Blackjack Rules
- 【愚公系列】2022年07月 Go教学课程 023-Go容器之列表
- 高通cDSP简单编程例子(实现查询高通cDSP使用率、签名),RK3588 npu使用率查询
- MySQL - multi-table query
猜你喜欢

Combinatorics Notes (6) Associative Algebra of Locally Finite Partially Ordered Sets, Möbius Inversion Formula

35 MySQL interview questions and diagrams, this is also easy to understand

全平台GPU通用AI视频补帧超分教程

Kotlin coroutines: continuation, continuation interceptor, scheduler

第七章

Apache EventMesh 分布式事件驱动多运行时

【PIMF】OpenHarmony 啃论文俱乐部—盘点开源鸿蒙三方库【3】

程序员如何学习开源项目,这篇文章告诉你

Architect 04 - Application Service Encryption Design and Practice

角色妆容的实现
随机推荐
抖音根据关键词取视频列表 API
Kotlin coroutines: continuation, continuation interceptor, scheduler
10 Ways to Keep Your Interface Data Safe
Architecture Battalion Module 8 Homework
Istio介绍
【公开课预告】:超分辨率技术在视频画质增强领域的研究与应用
【核心概念】图像分类和目标检测中的正负样本划分以及架构理解
基于STM32 环形队列来实现串口接收数据
Short-circuit characteristics and protection of SiC MOSFETs
1161. Maximum Sum of Elements in Layer: Hierarchical Traversal Application Problems
pytorch lstm时间序列预测问题踩坑「建议收藏」
spark报错OutOfMemory「建议收藏」
Write a database document management tool based on WPF repeating the wheel (1)
MySQL---创建和管理数据库和数据表
Apache EventMesh 分布式事件驱动多运行时
API for JD.com to obtain historical price information of commodities
关注!海泰方圆加入《个人信息保护自律公约》
&lt;artifactId&gt;ojdbc8&lt;/artifactId&gt;「建议收藏」
1161. 最大层内元素和 : 层序遍历运用题
GAC Honda Safety Experience Camp: "Danger" is the best teacher