java反射应用-配置文件的方式实例化对象


前言:本博客内容由张孝祥Java高新技术反射篇整理而来




项目目录结构



config.properties


classFileName=java.util.ArrayList



ReadPropertisToInstance.java


package com.dao.chu.movie;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Properties;

public class ReadPropertisToInstance {

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
		
		//1.getResourceAsStream直接获取 。带有‘/’表示绝对路径 否则为相对路径
		//InputStream in =ReflectTest2.class.getResourceAsStream("/spring/config.properties");
		//2.getClassLoader() 获取classpath路径
		InputStream in = ReadPropertisToInstance.class.getClassLoader().getResourceAsStream("spring/config.properties");
		Properties properties = new Properties();
		properties.load(in);
		in.close();
		
		String className = properties.getProperty("classFileName");
		Class<?> clazz = Class.forName(className);
		Collection collection=(Collection) clazz.newInstance();
		
		collection.add("1");
		collection.add("2");
		collection.add("3");
		
		System.out.println(collection.size());
		
	}
}


运行结果:

3


说明获取到了ArrayList的实例对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值