java反射

来源:互联网 发布:mac safari无痕模式 编辑:程序博客网 时间:2024/06/15 22:12

前言:为什么要学习反射,反射可以在程序运行的时候,动态的创建对象,那么这一个特性有什么好处呢?

              1.可以实现让框架替代我们创建对象,而且只创建一次,将其放到map中进行管理,需要的时候再拿出来用,可以防止写代码不规范,频繁的创建对象,导致内存泄漏

              2.可以减少代码的冗余,例如在web中,我们常会频繁的操作数据库,数据库的操作操作无非就是增删改查,以前我们会为每一个实体类都写一个操作数据库的dao,

                通过泛型,我们可以做如下的操作

               Class UserDao extends BaseDao<User>        

                 有了泛型,所有的Dao通过继承就可以共享BaseDao中的方法了,同时向BaseDao中动态传入实体类型,BaseDao解析实体类型,得到其字节码文件,再通过反射

                从字节码文件中得到我们想要的东西,比如类的属性字段的名称和值,通过动态的拼接不同的sql语句,就可以实现增删改查操作。


说了这么多,先解决一下第一个问题,其实也就是模拟一个简单的ioc

      1.模拟Ioc

            在模拟ioc容器时,我们要思考如下两个问题

            1.如何动态的获取我们需要的所有的字节码文件

            2.通过反射创建好对象,我们该如何进行管理


           //现在就第一个问题进行探讨

           通过我们配置的方式,将我们要创建的对象的信息放在其中,通过解析配置文件,得到字节码对应的字节码文件,动态的创建对象

          1.通过Properties文件进行配置

public class ReaderConfigureUtil { Properties pro; Map<String, Object> myMap; private static ReaderConfigureUtil rcu; private Class<?> c; private ReaderConfigureUtil(){ init(); } //懒汉式 public static ReaderConfigureUtil getInstance(){  if(rcu==null){  rcu=new ReaderConfigureUtil();  }  return rcu; } public void init(){// 1.得到文件的路径String path = this.getClass().getClassLoader().getResource("ioc.properties").getPath();myMap = new HashMap<String, Object>();FileInputStream fi = null;// 创建一个属性类pro = new Properties();// 创建流对象try {fi = new FileInputStream(path);// 加载配置文件pro.load(fi);} catch (Exception e) {e.printStackTrace();} finally {// 关闭资源if (fi != null) {try {fi.close();} catch (IOException e) {e.printStackTrace();}}}  }// 通过map装载数据public  void LoadingObject() {// 得到属性名,Enumeration<?> e = pro.propertyNames();String url = null;Object obj=null;String key=null;// 如果此枚举至少一个对象的时候,将返回下一个属性值while (e.hasMoreElements()) {//记录keyString name;name=e.nextElement().toString();if(name.equals("id")){key=pro.getProperty(name);myMap.put(key, obj);}else if(name.equals("Class")){    url=pro.getProperty(name);obj=CreateObject(url);}}System.out.println(myMap);}/* * 从Map中得到对象,key为键值 * */public Object getObject(String key){return myMap.get(key);}private  Object CreateObject(String url){Object o=null;try { c=Class.forName(url); //实例化对象 o= c.newInstance();} catch (Exception e) {e.printStackTrace();}return o;}}


//测试类
public class PropertiesTest {private ReaderConfigureUtil rcu;@Testpublic void test() {// 创建工具类rcu = ReaderConfigureUtil.getInstance();// 装载数据rcu.LoadingObject();// 取值System.out.println(rcu.getObject("user"));}}
结果如下


      

2.通过xml方式进行配置

2.1配置xml

<?xml version="1.0" encoding="UTF-8"?><beans>     <bean id="user" class="org.zh.bean.User">       <property name="id" value="1"></property>          <property name="name" value="xiaozhou"></property>          <property name="sex" value="男"></property>        </bean>     <bean id="book" class="org.zh.bean.Book">       <property name="id" value="2"></property>          <property name="name" value="西游记"></property>          <property name="price" value="20.3"></property>        </bean></beans>

2.2创建解析xml的类将xml文件中的信息封装为map对象

package org.zh.XmlUtil;import java.io.File;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NodeList;/* * 解析xml * *///使用w3Dom解析public class ParseConfigreUtil {private List<Bean> beanList;private static ParseConfigreUtil parseConfigreUtil = new ParseConfigreUtil();// 使用mapprivate Map<String, Object> beanMap;private ParseConfigreUtil() {beanList = new ArrayList<Bean>();beanMap=new HashMap<String,Object>();}public static ParseConfigreUtil getInstance() {return parseConfigreUtil;}public List<Bean> parse() {// 创建一个文档解析器生产的工厂DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();// 创建文档解析器对象try {DocumentBuilder builder = factory.newDocumentBuilder();// 得到文档对象Document doc = builder.parse(new File("src/bean.xml"));// 得到bean节点NodeList list = doc.getElementsByTagName("bean");// 遍历所有的节点int length = list.getLength();for (int i = 0; i < length; i++) {Element element = (Element) list.item(i);Bean bean = new Bean();bean.setId(element.getAttribute("id"));bean.setC(Class.forName(element.getAttribute("class")));NodeList nodeList = element.getElementsByTagName("property");Map<String, String> pro = new HashMap<String, String>();for (int j = 0; j < nodeList.getLength(); j++) {Element property = (Element) nodeList.item(j);pro.put(property.getAttribute("name"),property.getAttribute("value"));}bean.setPropertys(pro);beanList.add(bean);//创建对象CreateObject();}} catch (Exception e) {e.printStackTrace();}return beanList;}// 创建对象,并设置属性public void CreateObject() {// 通过强制for循环遍历,动态的创建对象,之后将对象封装到Map中for (Bean bean : beanList) {try {Class<?> c = bean.getC();Object o = c.newInstance();Method[] methods = c.getDeclaredMethods();for (int i = 0; i < methods.length; i++) {String methodName = methods[i].getName();if (methodName.contains("set")) {//切割methodName字符串String subString=methodName.substring(3,methodName.length()).toLowerCase();                        String type=methods[i].getParameterTypes()[0].getName();                        //得到value                        String value=bean.getPropertys().get(subString);                        Object obj=null;                        obj=DataChange.changeDataType(type, value);methods[i].setAccessible(true);methods[i].invoke(o,obj);}// 制空,避免内存泄漏methodName = null;}//添加对象    beanMap.put(bean.getId(),o);} catch (Exception e) {e.printStackTrace();}}}//让调用者通过getBean的方式得到对象,key为Xml中配置的idpublic Object getBean(String key){return beanMap.get(key);}}

方法参数类型转换的类package org.zh.XmlUtil;public class DataChange {//处理类型之间的转换public static Object changeDataType(String type,String value){Object obj=null;if(type.equals("java.lang.String")){obj=value;}else if(type.equals("int")){obj=Integer.parseInt(value);}else if(type.equals("float")){obj=Float.parseFloat(value);}//如果是其他类型,目前不做处理,后期有需要可以处理else{try {throw new Exception();} catch (Exception e) {System.out.println("您配置的参数有错误");}}return obj;}}

package org.zh.XmlUtil;import java.util.Map;final class Bean {// id是用来保存配置中的Id名称,class保存的是需要创建的对象的字节码,map中保存的是对象要设置的属性private String id;private Class<?> c;private Map<String, String> propertys;public String getId() {return id;}public void setId(String id) {this.id = id;}public Class<?> getC() {return c;}public void setC(Class<?> c) {this.c = c;}public Map<String, String> getPropertys() {return propertys;}public void setPropertys(Map<String, String> propertys) {this.propertys = propertys;}}

//测试类

package org.zh.XmlUtil;import org.junit.Test;import org.zh.bean.Book;import org.zh.bean.User;public class test {@Testpublic void testName() throws Exception {//创建单例的工具解析类ParseConfigreUtil p=ParseConfigreUtil.getInstance();p.parse();//得到user对象User user=(User)p.getBean("user");System.out.println("user对象:"+user.getId()+","+user.getName()+","+user.getSex());Book book=(Book)p.getBean("book");System.out.println("user对象:"+book.getId()+","+book.getName()+","+book.getPrice());}}
测试结果


3.创建通用的dao   BaseDao,简单的模拟了添加数据的方法,大家有兴趣的话,可以自己试着不写一个查询,删除,更新等方法
package org.zh.test;//http://www.cnblogs.com/RGogoing/p/5325196.htmlimport java.lang.reflect.ParameterizedType;@SuppressWarnings("unchecked")     //不提示警告public  class BaseDaoImpl<T> implements BaseDao<T> {Class<T> c;public BaseDaoImpl(){    ParameterizedType type=(ParameterizedType)this.getClass().getGenericSuperclass();//得到的是当前对象父类的类型    //得到了实际类型的定义,字节码文件    c= (Class<T>)type.getActualTypeArguments()[0];                                //得到父类中传入的参数}
public void add(T t) {<span style="white-space:pre"></span> JdbcDao.save((Object)t);<span style="white-space:pre"></span>}}

//操作数据库连接,拼接sql

package org.zh.test;import java.lang.reflect.Field;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import org.zh.util.DBManger;//实现对数据的解析,执行增删改查操作public class JdbcDao {/* 这些常量的意思区分不同的操作,因为插入和删除记录,sql语句是不一样的,同时替代占位符位置的数据的个数也是不一样的  insert into person(id,name,sex)value(1,'xiaozhou','男');  delete from person where id=1;*/private static final String ADD_OBJECT="add";//private static final String DELETE_OBJECT="delete";//private static final String UPDATE_OBJECT="update";//private static final String SELECT_OBJECT="select";private static Class<?> c;    public static void save(Object obj){     c=obj.getClass();     Connection con=DBManger.getConnect();     PreparedStatement pre=null;     ResultSet res=null;     try {     //对sql进行预编译         String sql=linkSql(ADD_OBJECT); pre=con.prepareStatement(sql); Object [] data=setArgs(ADD_OBJECT,obj); parseData(pre,data); int row=pre.executeUpdate(); if(row>0){ System.out.println("保存成功");   }    } catch (SQLException e) {     e.printStackTrace();    }finally{     DBManger.closeAll(res,pre,con);}}        //向PreparedStatement中添加数据,就是替代占 位符的数据,insert into person(id,name,sex)values(?,?,?);    private static void parseData(PreparedStatement pre,Object[]data){    int length=data.length;    for(int i=0;i<length;i++){    try {pre.setObject(i+1,data[i]);} catch (SQLException e) {e.printStackTrace();}    }    }      //根据不同的操作来拼接sql语句    private  static String linkSql(String operate) {    StringBuffer buffer=new StringBuffer();    if(operate.equals(ADD_OBJECT)){    buffer.append("insert into "+c.getSimpleName());      //insert into emp(id,name,sex)values(?,?,?)    buffer.append("(");    //从字节码中得到所有的字段     Field []fields=c.getDeclaredFields();     System.out.println(fields.length);    //强制循环得到所有字段名    for(Field f:fields){    f.setAccessible(true);    buffer.append(f.getName());    System.out.println(f.getName());    buffer.append(",");    }    //删除指定位置的字符,就是删除多出的,号    buffer.deleteCharAt(buffer.length()-1);     buffer.append(") values(?,?,?) ;");    System.out.println(buffer.toString());    //返回sql语句    return buffer.toString();    }        else{        try {throw new Exception();} catch (Exception e) {System.out.println("您所给的参数不匹配");}        }    return buffer.toString();    }    private  static Object[] setArgs(String operate,Object o){    //得到t中的值,因为 增删改查的时候所要取得的值是不一样的    Object [] obj=null;    if(operate.equals(ADD_OBJECT)){    //通过反射得到有多少个字段就产生多大的对象数组,效率较高    Field []fields=c.getDeclaredFields();    int length=fields.length;    obj=new Object[length];    for(int i=0;i<length;i++){    try {    fields[i].setAccessible(true);obj[i]=fields[i].get(o);} catch (IllegalArgumentException | IllegalAccessException e) {e.printStackTrace();}    }    }    return obj;    }   }


package org.zh.test;public class Person {     private int id;     private String name;     private String sex;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}     }

现在我们要建立一个用于操作person类的dao 只要继承BaseDao就可以了,如下所示

public  PersonDao extends BaseDao<Person>



下面是测试类

package org.zh.test;import org.junit.Test;public class DaoTest {     @Testpublic void test() throws Exception {Person p=new Person();p.setId(7);p.setName("xiao ming");p.setSex("男");PersonDao personDao=new PersonDaoImpl();personDao.add(p);}}
测试结果如下:

 本人技术比较菜,如有大神发现错误请指点,谢谢大家!                                                                                                        









2.1配置xml
2 0
原创粉丝点击