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. Visual Studio for mac从入门到放弃1

    MAC  第一步:从微软官网下载:https://www.visualstudio.com/vs/visual-studio-mac/ 第二步:安装软件过程出现 It was not possible ...

  2. C#注册表操作类(完整版) 整理完整

    /// <summary> /// 注册表基项静态域 /// /// 主要包括: /// 1.Registry.ClassesRoot 对应于HKEY_CLASSES_ROOT主键 /// ...

  3. SharePoint Caml Query 使用

    需要注意的是: 再使用ListQueryWebPart部件时,默认查看的list列表会出现乱码的情况,需要开启服务器呈现模式,如图: 特此记录一下

  4. windows下用wampServer 为wordpress 搭建本地服务器运行环境

      1.准备wamp server wamp是windows apache mysql php 的首字母缩写,更新的wamp总能保证wordpress对服务器的要求 点此下载最新wamp 2.安装wa ...

  5. JAVA异常的最佳工程学实践探索

    此文已由作者占金武授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 先说明一下背景: 项目日志中的Exception会被哨兵统一监控并报警 比较多的项目基于dubbo在做服务化 ...

  6. 自动统计安卓log中Anr,Crash,Singnal出现数量的Python脚本 (转载)

    自动统计安卓log中Anr,Crash,Singnal出现数量的Python脚本   转自:https://www.cnblogs.com/ailiailan/p/8304989.html 作为测试, ...

  7. Elasticsearch学习(5) Elasticsearch+logstash +filebeat+log4j的日志系统

    最近需要使用Elasticsearch做一个日志系统,本文只介绍log4j内容同步到Elasticsearch,至于日志的查询和分类,会在后面介绍. 一.配置并打开Elasticsearch 这个操作 ...

  8. 【ocp-12c】最新Oracle OCP-071考试题库(44题)

    44.(9-12)choose all that apply View the Exhibit and examine the details of the ORDER_ITEMS table. Ev ...

  9. mybatis pagehelper多数据源配置的坑

    我用spring boot配置了2个数据源的工程用来同步不同库的数据,发现如果配置成如下格式报错 #分页配置pagehelper: helper-dialect: mysql reasonable: ...

  10. dubbo服务器启动后报错端口被占用

    环境:maven工程,ssm框架,tomcat 情景:dubbo的服务注册方服务器启动 问题原因: 经过网络查找,结果是Root WebApplicationContext 启动了两次,第二次报错,d ...