package com.dys.util;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import com.dys.annotation.DysAnnotation;
import com.dys.model.BeanDefinition;
import com.dys.model.PropertyDefinition; public class XMLUtils {
private List<BeanDefinition> beanDefinitions = new ArrayList<BeanDefinition>();
private Map<String, Object> singletons = new HashMap<String, Object>();
public XMLUtils(String fileName) {
this.readXML(fileName);
this.initilizeBeans();
this.annotationInject();
this.injectObject();
}
private void annotationInject() {
try {
for(String beanName : singletons.keySet()) {
Object bean = singletons.get(beanName);
if(bean != null) {
PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();
for(PropertyDescriptor propertyDescriptor : propertyDescriptors) {
Method setMethod = propertyDescriptor.getWriteMethod();
if(setMethod != null && setMethod.isAnnotationPresent(DysAnnotation.class)) {
DysAnnotation dysA = setMethod.getAnnotation(DysAnnotation.class);
Object beanValue = null;
if(dysA.name() != null && !"".equals(dysA.name())) {
String name = dysA.name();
beanValue = singletons.get(name); } else {
String nam = propertyDescriptor.getName();
beanValue = singletons.get(nam);
if(beanValue == null) {
for(String key : singletons.keySet()) {
if(propertyDescriptor.getPropertyType().isAssignableFrom(singletons.get(key).getClass())) {
beanValue = singletons.get(key);
break;
}
}
}
}
setMethod.setAccessible(true);
setMethod.invoke(bean, beanValue);
}
}
}
Field[] fields = bean.getClass().getDeclaredFields();
for(Field field : fields) {
if(field != null && field.isAnnotationPresent(DysAnnotation.class)) {
DysAnnotation dysA = field.getAnnotation(DysAnnotation.class);
Object beanValue = null;
if(dysA.name() != null && !"".equals(dysA.name())) {
String name = dysA.name();
beanValue = singletons.get(name); } else {
String nam = field.getName();
beanValue = singletons.get(nam);
for(String key : singletons.keySet()) {
if(field.getType().isAssignableFrom(singletons.get(key).getClass())) {
beanValue = singletons.get(key);
break;
}
}
}
field.setAccessible(true);
field.set(bean, beanValue);
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
private void injectObject(){
try {
for(BeanDefinition beanDefinition:beanDefinitions) {
Object object = singletons.get(beanDefinition.getId());
if(object != null) {
PropertyDescriptor[] pds = Introspector.getBeanInfo(object.getClass()).getPropertyDescriptors();
for(PropertyDefinition propertyDefinition : beanDefinition.getProperties()) {
for(PropertyDescriptor pd : pds) {
if(propertyDefinition.getName().equals(pd.getName())) {
Method setMethod = pd.getWriteMethod();
if(setMethod != null) {
Object propertyV = singletons.get(propertyDefinition.getRef());
setMethod.setAccessible(true);
setMethod.invoke(object, propertyV);
}
break;
}
}
}
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
private void initilizeBeans() {
for(BeanDefinition beanDefinition : beanDefinitions) {
try {
if(beanDefinition.getName() != null && !"".equals(beanDefinition.getName().trim())) {
singletons.put(beanDefinition.getId(), Class.forName(beanDefinition.getName()).newInstance());
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
private void readXML(String filename) {
SAXReader saxReader = new SAXReader();
Document document = null;
try {
URL xmlpath = this.getClass().getClassLoader().getResource(filename);
document = saxReader.read(xmlpath);
Map<String, String> nsMap = new HashMap<String, String>();
nsMap.put("ns", "http://www.springframework.org/schema/beans");
XPath xsub = document.createXPath("//ns:beans/ns:bean");
xsub.setNamespaceURIs(nsMap);
List<Element> beans = xsub.selectNodes(document);
for(Element element:beans){
String id = element.attributeValue("id");
String clazz = element.attributeValue("class");
BeanDefinition beanDefinition = new BeanDefinition(id, clazz);
XPath xsubProperty = element.createXPath("ns:property");
xsubProperty.setNamespaceURIs(nsMap);
List<Element> propertyElement = xsubProperty.selectNodes(element);
for(Element ele:propertyElement) {
String name = ele.attributeValue("name");
String ref = ele.attributeValue("ref");
PropertyDefinition propertyDefinition = new PropertyDefinition(name, ref);
beanDefinition.getProperties().add(propertyDefinition);
}
beanDefinitions.add(beanDefinition);
}
}catch(Exception e) {
e.printStackTrace();
}
}
public Object getBean(String name) {
Object beanClass = singletons.get(name);
return beanClass;
}
}

反射 XMLUtil的更多相关文章

  1. 上次遗留下来的XMLUtil的问题

    ·在上周留下了一个关于XMLUtil的问题,问题大概是这样的,需要通过读取一个XML文件,然后在内存中生成一个对应的javaBean.之前写的那个很是糟糕,照着一个XML去写了一个"Util ...

  2. java反射机制的粗略理解

    java反射机制: 涉及的对象:Class, Object, 函数:Class类:[forName(String className):static:getClass():public],Object ...

  3. 抽象工厂模式(JAVA反射)

    实例代码(JAVA):模式动机     在工厂方法模式中具体工厂负责生产具体的产品,每一个具体工厂对应一种具体产品,工厂方法也具有唯一性,一般情况下,一个具体工厂中只有一个工厂方法或者一组重载的工厂方 ...

  4. 工厂方法模式(JAVA反射)

    简单工厂模式的不足     在简单工厂模式中,只提供了一个工厂类,该工厂类处于对产品类进行实例化的中心位置,它知道每一个产品对象的创建细节,并决定何时实例化哪一个产品类.简单工厂模式最大的缺点是当有新 ...

  5. dom4j+反射实现bean与xml的相互转换

    由于目前在工作中一直用的dom4j+反射实现bean与xml的相互转换,记录一下,如果有不正确的地方欢迎大家指正~~~ 一.反射机制 在此工具类中使用到了反射技术,所以提前也看了一些知识点,例如:ht ...

  6. 隐私泄露杀手锏 —— Flash 权限反射

    [简版:http://weibo.com/p/1001603881940380956046] 前言 一直以为该风险早已被重视,但最近无意中发现,仍有不少网站存在该缺陷,其中不乏一些常用的邮箱.社交网站 ...

  7. Java学习之反射机制及应用场景

    前言: 最近公司正在进行业务组件化进程,其中的路由实现用到了Java的反射机制,既然用到了就想着好好学习总结一下,其实无论是之前的EventBus 2.x版本还是Retrofit.早期的View注解框 ...

  8. 关于 CSS 反射倒影的研究思考

    原文地址:https://css-tricks.com/state-css-reflections 译者:nzbin 友情提示:由于演示 demo 的兼容性,推荐火狐浏览.该文章篇幅较长,内容庞杂,有 ...

  9. 编写高质量代码:改善Java程序的151个建议(第7章:泛型和反射___建议106~109)

    建议106:动态代理可以使代理模式更加灵活 Java的反射框架提供了动态代理(Dynamic Proxy)机制,允许在运行期对目标类生成代理,避免重复开发.我们知道一个静态代理是通过主题角色(Prox ...

随机推荐

  1. 在SQL Server 2008中执行透明数据加密

    问题 安全是任何公司的一个主要考量.数据库备份容易被偷并被恢复到另一个SQL Server实例上.当我们浏览SQL Server 2008的新特性时,我们对一个叫做透明数据加密的特性很感兴趣,我们可以 ...

  2. c# async 事物

    上菜 async await 机制 确实便捷开发   多线程时 如何一致性如何保证呢? public async Task<ActionResult<IEnumerable<stri ...

  3. Photoshop的脚本开发

    之前的博客的文章,贴过来了.PhotoshopCS开始增加了脚本.Photoshop的脚本可以用JavaScript,AppleScript以及VbScript和visualBasic.其中Apple ...

  4. 【转】如何成为一名优秀的web前端工程师(前端攻城师)?

    [转自]http://julying.com/blog/how-to-become-a-good-web-front-end-engineer/ 程序设计之道无远弗届,御晨风而返.———— 杰佛瑞 · ...

  5. 和我一起学python

    近来python越来越火,很多人都出了教程,我也来出一个凑凑热闹吧. pycharm激活 http://idea.lanyus.com/ https://blog.csdn.net/u01404481 ...

  6. A - 还是畅通工程(最小生成树)

    点击打开链接 某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离.省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并 ...

  7. Problem I: GJJ的日常之玩游戏(GDC)

    Contest - 河南省多校连萌(四) Problem I: GJJ的日常之玩游戏 Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 107  Solve ...

  8. Java多线程(汇聚页)

    Java多线程(汇聚页) Java多线程总结

  9. python学习笔记-控制流(if for while break continue)

    if语句 if语句用以检查条件:如果条件为真(True),将运行一块语句(称作 if-block 或 if 块),否则将运行另一块语句(称作 else-block 或 else 块).其中else 从 ...

  10. 基于Dubbo的Hessian协议实现远程调用

    Dubbo基于Hessian实现了自己Hessian协议,可以直接通过配置的Dubbo内置的其他协议,在服务消费方进行远程调用,也就是说,服务调用方需要使用Java语言来基于Dubbo调用提供方服务, ...