基本概念:
Java中提供了一套API用来访问某个属性的getter/setter方法,通过这些API可以使你不需要了解这个规则,这些API存放于包java.beans中,一般的做法是通过类Introspector的getBeanInfo方法来获取某个对象的BeanInfo信息,然后通过BeanInfo来获取属性的描述器(PropertyDescriptor),通过这个属性描述器就可以获取某个属性对应的getter/setter方法,然后我们就可以通过反射机制来调用这些方法.
例子:
//创建类Config
public class Config { private String username; private String password; private String url; public Config() { } public Config(String username, String password, String url) { this.username = username; this.password = password; this.url = url; } @Override public String toString() { return "Config{" + "username='" + username + '\'' + ", password='" + password + '\'' + ", url='" + url + '\'' + '}'; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
//生成Config.properties配置文件
Config.bean=com.clayfan.Config.Config Config.username=tom Config.password=123456 Config.url=https://www.baidu.com
//生成工厂对象
public class BeanFactory { private static Properties pro = new Properties(); static{ InputStream resourceAsStream = Thread.currentThread() .getContextClassLoader().getResourceAsStream("com/clayfan/Config/Config.properties"); try { pro.load(resourceAsStream); } catch (IOException e) { e.printStackTrace(); } } public static Object getBean(String name){ String bean = pro.getProperty(name); Object target = null; try { Class<?> aClass = Class.forName(bean); target= aClass.newInstance(); BeanInfo beanInfo = Introspector.getBeanInfo(aClass); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { String propername = propertyDescriptors[i].getName(); Method writeMethod = propertyDescriptors[i].getWriteMethod(); if("username".equals(propername)){ writeMethod.invoke(target,pro.getProperty("Config.username")); }else if ("password".equals(propername)){ writeMethod.invoke(target,pro.getProperty("Config.password")); }else if("url".equals(propername)){ writeMethod.invoke(target,pro.getProperty("Config.url")); } } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IntrospectionException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return target; } }
//测试
public class BeanFactoryTest { @Test public void test(){ Config bean = (Config)BeanFactory.getBean("Config.bean"); System.out.println(bean); } }