java 工厂设计模式(通过反射)

需求:从一个配置文件中读取预设好的类和属性来创建一个对象

import java.lang.reflect.*;
import java.lang.reflect.InvocationTargetException;
import java.security.KeyStore.Entry;
import java.util.*;
import com.wxhl.jq0804.Person;
public class Demo07 {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException, IOException {
        Person p = (Person)getInstance("D:/Person.properties");
        System.out.println(p);
    }

    public static Object getInstance(String path) throws IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException{
        //创建配置文件
        Properties properties = new Properties ();
        //创建管道
        FileReader fileReader = new FileReader(path);
        //加载配置文件
        properties.load(fileReader);
        //从配置文件中创建Class类
        String className = properties.getProperty("class");
        Class clazz = Class.forName(className);
        Constructor constructor = clazz.getConstructor(); 
        Object obj = constructor.newInstance();
        //遍历配置文件
        Set> entrySet = properties.entrySet();
        for(java.util.Map.Entry entry : entrySet){
            String tmp = (String)entry.getKey();
            if ("class".equals(entry.getKey())){//之前使用了这个key,所以这里得跳过
                continue;
            }
            //获取所有属性(包括私有)
            Field field = clazz.getDeclaredField((String) entry.getKey());
            field.setAccessible(true);
            //为属性赋值
            if (field.getType()==int.class){
                field.set(obj, Integer.parseInt((String) entry.getValue()));
            }else if (field.getType()==float.class){
                field.set(obj, Float.parseFloat((String) entry.getValue()));
            }else if (field.getType()==double.class){
                field.set(obj, Double.parseDouble((String) entry.getValue()));
            }else if (field.getType()==boolean.class){
                field.set(obj, Boolean.parseBoolean((String) entry.getValue()));
            }else{
                field.set(obj, (String) entry.getValue());
            }
    
        }
        return obj;
    }
}

配置文件

Paste_Image.png

你可能感兴趣的:(java 工厂设计模式(通过反射))