需求:
通过反射的方式读取配置文件中配置的集合,然后根据配置文件中所配置的集合来输出集合中的元素个数
- package test;
- import java.util.*;
- import java.io.*;
- public class Test01
- {
- public static void main(String[] args) throws Exception
- {
- //创建一个读取配置文件的输入流
- InputStream ips = new FileInputStream("config.properties");
- //创建一个Properties对象和输入流关联,把配置文件的内容读取到集合中
- Properties props = new Properties();
- props.load(ips);
- ips.close();
- //得到键值
- String className = props.getProperty("className");
- //通过反射的方式创建集合
- Collection con = (Collection) Class.forName(className).newInstance();
- //Collection con = new ArrayList();
- ClassDemo cd1 = new ClassDemo(9,8);
- ClassDemo cd2 = new ClassDemo(1,8);
- ClassDemo cd3 = new ClassDemo(9,8);
- con.add(cd1);
- con.add(cd2);
- con.add(cd3);
- con.add(cd1);
- System.out.println(con.size());
-
-
- }
- }
- class ClassDemo
- {
- private int x;
- private int y;
- public ClassDemo(int x, int y) {
- super();
- this.x = x;
- this.y = y;
- }
- public int getX() {
- return x;
- }
- public void setX(int x) {
- this.x = x;
- }
- public int getY() {
- return y;
- }
- public void setY(int y) {
- this.y = y;
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + x;
- result = prime * result + y;
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- final ClassDemo other = (ClassDemo) obj;
- if (x != other.x)
- return false;
- if (y != other.y)
- return false;
- return true;
- }
-
- }
复制代码 当配置文件为:
className = java.util.ArrayList
时,输出结果为4
当配置文件为:
className = java.util.HashSet
时,输出结果为2
|
|