您的位置:首页 > 编程语言 > Java开发

用类加载器的方式管理资源和配置文件

2018-01-29 00:00 567 查看

一、概述

1、相对路径中“相对”的含义



2、尽可能使用绝对路径,一定要记住用完整路径,但完整路径不是硬编码,而是通过运算

3、代码说明

package staticimport.reflect;

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

public class HashCodeReflectTest {

public static void main(String[] args) throws Exception {

//getRealPath()//金山词霸,获取内部绝对地址
//一定要记住用完整路径,但完整路径不是硬编码,而是通过运算
//通过相对路径(不推荐)或绝对路径
//		InputStream is = new FileInputStream("config.properties");
//类加载器加载资源文件
//		InputStream is = HashCodeReflectTest.class.getClassLoader().getResourceAsStream("staticimport/reflect/config.properties");
//类本身加载资源文件(相对路径方式)
//		InputStream is = HashCodeReflectTest.class.getResourceAsStream("config.properties");
//类本身加载资源文件(相对路径方式)
//		InputStream is = HashCodeReflectTest.class.getResourceAsStream("resource/config.properties");
//类本身加载资源文件(绝对路径方式)前面一定要加/
InputStream is = HashCodeReflectTest.class.getResourceAsStream("/staticimport/reflect/resource/config.properties");
Properties props = new Properties();
props.load(is);

String className = props.getProperty("className");

Collection<ReflectPoint> reflectPoints = (Collection<ReflectPoint>) Class.forName(className).newInstance();

//		Collection<ReflectPoint> reflectPoints = new ArrayList<>();
//		Collection<ReflectPoint> reflectPoints = new HashSet<>();
ReflectPoint reflectPoint = new ReflectPoint(3, 3);
ReflectPoint reflectPoint2 = new ReflectPoint(5, 6);
ReflectPoint reflectPoint3 = new ReflectPoint(3, 3);

//测试hashCode作用
reflectPoints.add(reflectPoint);
reflectPoints.add(reflectPoint2);
reflectPoints.add(reflectPoint3);
reflectPoints.add(reflectPoint);

//测试内存泄漏
//		reflectPoint.y = 12;
//		reflectPoints.remove(reflectPoint);

System.out.println(reflectPoints.size());
}

}

注:如ssh框架的资源文件大都通过本文方式进行加载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息