类加载器classLoader加载配置文件多种方法,框架原理--反射

来源:互联网 发布:关系数据库语言 编辑:程序博客网 时间:2024/05/21 11:37
public class FrameReflect {@SuppressWarnings("unchecked")public static void main(String[] args) {try {/** * 如果直接将配置文件放在项目文件夹中,但是一般这种情况,不利于将class文件打包给客户,所以讲配置文件放在源文件src目录 * 这样MyEclipse会自动将配置文件放在class目录中。(禁用) * InputStream input = new FileInputStream("config.properties"); * 将配置文件放入包中之后,这种方式相对不能得到绝对路径,不提倡使用: * InputStream input = new FileInputStream("src/com/interview/frameReflect/config.properties"); * 通过类加载器: * InputStream input = FrameReflect.class.getClassLoader().getResourceAsStream("com/interview/frameReflect/config.properties"); * 而class类一般都是用类加载器加载进来的,我们可以直接用类的加载器,直接用的时候,路径就是为相对于本类(FrameReflect)的路径 * InputStream input = FrameReflect.class.getResourceAsStream("config.properties"); * 当然是可以不相对于路径,这就要在前面加上/和路径名了,不过这种方法对于配置文件路径完全与本类的路径无关的情况 * InputStream input = FrameReflect.class.getResourceAsStream("/com/interview/frameReflect/config.properties"); */InputStream input = FrameReflect.class.getResourceAsStream("/com/interview/frameReflect/config.properties");Properties properties = new Properties();properties.load(input);//通过配置文件得到类名String className = properties.getProperty("className");//利用反射技术初始化类名Collection collection = (Collection)Class.forName(className).newInstance();MyPoint p1 = new MyPoint(5, 6);MyPoint p2 = new MyPoint(3, 2);MyPoint p3 = new MyPoint(5, 8);MyPoint p4 = new MyPoint(5, 6);collection.add(p1);collection.add(p2);collection.add(p3);collection.add(p4);System.out.println("集合的大小为:"+collection.size());} catch (Exception e) {System.out.println("配置文件未找到!!!");}}}

config.properties配置文件内容:

className =java.util.HashSet


实现从配置文件加载类,并通过反射技术得到类的实例----框架的基本原理

来源视频:张孝祥老师----28_用类加载器的方式管理资源和配置文件

0 0