当前位置:网站首页>利用反射实现一个管理对象信息的简单框架
利用反射实现一个管理对象信息的简单框架
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类型的属性,其它属性等我有空再写~ 感觉不是很好弄。
目前只能管理对象一个对象,多个对象有待实现
边栏推荐
- MySQL---operator
- leetcode 665. Non-decreasing Array
- How can we improve the real yourself, become an excellent architect?
- leetcode 665. Non-decreasing Array 非递减数列(中等)
- Redis综述篇:与面试官彻夜长谈Redis缓存、持久化、淘汰机制、哨兵、集群底层原理!...
- MySQL---排序与分页
- spark报错OutOfMemory「建议收藏」
- Architecture Battalion Module 8 Homework
- 请问我的这段sql中sql语法哪里出了错
- 全平台GPU通用AI视频补帧超分教程
猜你喜欢

MySQL---多表查询

角色妆容的实现

1161. Maximum Sum of Elements in Layer: Hierarchical Traversal Application Problems

Basic configuration of OSPFv3

The whole network is on the verge of triggering, and the all-round assistant for content distribution from media people - Rongmeibao

如何才能真正的提高自己,成为一名出色的架构师?

Architect 04 - Application Service Encryption Design and Practice

Apache EventMesh distributed event-driven multi-runtime

How can we improve the real yourself, become an excellent architect?

Arduino框架下STM32全系列开发固件安装指南
随机推荐
rj45对接头千兆(百兆以太网接口定义)
嵌入式开发没有激情了,正常吗?
常用的安全渗透测试工具(渗透测试工具)
返回一个零长度的数组或者空的集合,不要返回null
淘宝/天猫获得淘口令真实url API
【Yugong Series】July 2022 Go Teaching Course 025-Recursive Function
Memblaze发布首款基于长存颗粒的企业级SSD,背后有何新价值?
API for JD.com to obtain historical price information of commodities
Batch (batch size, full batch, mini batch, online learning), iterations and epochs in deep learning
Bika LIMS open source LIMS set - use of SENAITE (detection process)
2022年Android 面经总结(附含面试题 | 源码 | 面试资料)
Short-circuit characteristics and protection of SiC MOSFETs
MySQL---子查询
-xms -xmx(information value)
程序员如何学习开源项目,这篇文章告诉你
&lt;artifactId&gt;ojdbc8&lt;/artifactId&gt;「建议收藏」
Combinatorics Notes (6) Associative Algebra of Locally Finite Partially Ordered Sets, Möbius Inversion Formula
Get Douyin Video Details API
PCB叠层设计
PCB stackup design