前言:本博客內容由張孝祥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的實例對象