</pre><pre name="code" class="java">[code=Java]
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Person
{
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String toString()
{
return "name: " + name + " id: " + id;
}
}
class Bean
{
private String id;
private String type;
private Map<String, Object> properties = new HashMap<String, Object>();
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
public Map<String, Object> getProperties() {
return properties;
}
}
public class BeanFactory
{
//保存生成的类实例,键为String,值为Object
private Map<String, Object> beanMap = new HashMap<String, Object>();
//构造函数解析配置好的bean,相当于sping中解析xml配置文件
public BeanFactory(List<Bean> beans)
{
try
{
for(Bean bean : beans)
{
Class<?> clazz = Class.forName(bean.getType());
//生成类
Object obj = clazz.newInstance();
Method[] methods = clazz.getMethods();
for(String name : bean.getProperties().keySet())
{
StringBuilder sb = new StringBuilder(name);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
String methodName = sb.toString();
methodName = "set" + methodName;
for(Method method : methods)
{
//通过set方法设置类的属性
if(method.getName().equals(methodName))
method.invoke(obj, bean.getProperties().get(name));
}
}
//将生成好的类放入beanMap
beanMap.put(bean.getId(), obj);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
//获得bean
public Object getBean(String id)
{
return beanMap.get(id);
}
public static void main(String[] args)
{
ArrayList<Bean> beans = new ArrayList<Bean>();
Bean bean = new Bean();
//生成bean的配置信息,相当于配置xml文件
bean.setId("person");
bean.setType("Person");
Map<String, Object> properties = new HashMap<String, Object>();
//配置属性
properties.put("name", "Alice");
properties.put("id", 11);
bean.setProperties(properties);
beans.add(bean);
//解析配置好的bean
BeanFactory factory = new BeanFactory(beans);
//获取person类
Person person = (Person) factory.getBean("person");
System.out.println(person);
}
}
[/code]
123
最新推荐文章于 2021-04-30 16:20:48 发布