您的位置:首页 > 其它

从配置文件中获取类名,利用反射创建对象

2014-03-12 09:23 603 查看
----------------------
ASP.Net+Unity开发、.Net培训、期待与您交流! ----------------------

public class PropertiesTest {

/**

* 使用反射技术开发框架

* 把需要创建的类写到配置文件中,通过反射创建类的对象,好处在于不需要修改代码,就可以改变建立的对象。

* 获取文件的路径一定要用完整的路径,完整的路径是计算出来的。

*/

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

// InputStream ips=new FileInputStream("config.properties");////得到配置文件流的第一种方法

// InputStream ips=Test1.class.getClassLoader().getResourceAsStream("com/tsh/gaoxin/config1.properties");//使用类加载器获取字节流,路径是在CLASSPATH路径下开始,开头不能加‘/’

// InputStream ips=PropertiesTest.class.getResourceAsStream("peizhi/config1.properties");//字节码本身也有获取字节流的方法,其实底层就是调用类加载器的方法。

InputStream ips=PropertiesTest.class.getResourceAsStream("/com/tsh/gaoxin/peizhi/config1.properties");//带'/'开头代表是绝对路径,不带的是相对路径。

Properties pro=new Properties();

pro.load(ips);//加载配置文化

ips.close();//关闭输入流

String classname=pro.getProperty("classname");//获取配置文件key对应的值

//使用反射创建实例对象

Collection<String> collection=(Collection<String>) Class.forName(classname).newInstance();

collection.add("11");

collection.add("22");

collection.add("33");

System.out.println(collection.toString());

}

}

----------------------
ASP.Net+Unity开发、.Net培训、期待与您交流! ----------------------详细请查看:http://edu.csdn.net
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐