java的反射加载配置文件,利用java 反射获取配置文件并将对应内容赋值给对应的类...

单元测试与配置加载
本文介绍了一种通过单元测试加载配置文件的方法,并演示了如何利用反射机制为对象属性赋值的过程。具体步骤包括:加载配置文件、解析配置项并根据属性类型转换值,最后通过反射调用setter方法完成赋值。

单元测试如下

public class DataSourceModelTest {

@Test

public void test1() throws Exception {

//创建一个对象,用于赋值操作

DataSourceModel model = new DataSourceModel();

//加载配置文件()

InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.propertise");

Properties properties = new Properties();

//使用缓存流进行加载

properties.load(new BufferedInputStream(inputStream));

//获取配置类的Class对象对应的所有方法

Method[] methods = DataSourceModel.class.getMethods();

for (Method method : methods) {

//获取方法名称

String methodName = method.getName();

//判断方法前缀是否是set开头

if (methodName.startsWith("set")) {

//获取userName中的serName

String afterName = methodName.substring(4);

//获取属性第一个字母,也就是setUserName中的U

String firstName = methodName.substring(3, 4);

String newName = firstName.toLowerCase() + afterName;

String property = properties.getProperty(newName);

if (!Objects.isNull(property)) {

//获取方法形参类型

Class>[] parameterTypes = method.getParameterTypes();

String sn = parameterTypes[0].getSimpleName();

Object arg = null;

//判断属于那种数据类型

if (sn.equals("int") || sn.equals("Integer")) {

arg = Integer.parseInt(property);

} else if (sn.equals("long") || sn.equals("Long")) {

arg = Long.parseLong(property);

} else if (sn.equals("double") || sn.equals("Double")) {

arg = Double.parseDouble(property);

} else if (sn.equals("boolean") || sn.equals("Boolean")) {

arg = Boolean.parseBoolean(property);

} else if (sn.equals("float") || sn.equals("Float")) {

arg = Float.parseFloat(property);

} else if (sn.equals("String")) {

arg = property;

} else {

continue;

}

//反射赋值

method.invoke(model, arg);

}

}

}

//输出

System.out.println("model = " + model);

}

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值