package com.cn.mybatis.test; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Date; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.cn.mybatis.model.EdiTestTask; public class mybatisTest { public static void main(String[] args) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ //mybatis的配置文件 String conf="conf.xml"; //使用类加载器加载mybatis的配置文件(它也加载关联的映射文件) InputStream is=mybatisTest.class.getClassLoader().getResourceAsStream(conf); //构建sqlSession的工厂 SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(is); SqlSession session=sessionFactory.openSession(); String statement="com.cn.mybatis.mapper.taskMapper.getAllTask"; EdiTestTask editt=session.selectOne(statement,"6c61bffed61141d7a908af0428ae57fb"); if(editt!=null){ Field[] field = editt.getClass().getDeclaredFields(); for (int i = 0; i < field.length; i++) { String name=field[i].getName(); //获得对象的属性名称 String type=field[i].getGenericType().toString(); System.out.println("属性的类型:"+type); name=name.substring(0,1).toUpperCase()+name.substring(1); //构造get方法的名字 Method m=editt.getClass().getMethod("get"+name); if(type.equals("int")||type.equals("class java.lang.Integer")){ //如果type是类类型,则前面包含"class ",后面跟类名 int val=(Integer)m.invoke(editt); System.out.println(name+"的值:"+val); } if(type.equals("class java.lang.String")){ String val=(String)m.invoke(editt); System.out.println(name+"的值:"+val); } if(type.equals("class java.lang.Short")){ Short value = (Short) m.invoke(editt); if(value != null){ System.out.println("attribute value:"+value); } } if(type.equals("class java.lang.Double")){ Double value = (Double) m.invoke(editt); if(value != null){ System.out.println("attribute value:"+value); } } if(type.equals("class java.lang.Boolean")){ Boolean value = (Boolean) m.invoke(editt); if(value != null){ System.out.println("attribute value:"+value); } } if(type.equals("class java.util.Date")){ Date value = (Date) m.invoke(editt); if(value != null){ System.out.println("attribute value:"+value.toLocaleString()); } } } } } }
时间: 2024-10-27 10:55:54