对javabean的内省操作及常用工具类

来源:互联网 发布:java获取传感器数据 编辑:程序博客网 时间:2024/05/14 22:09

 

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

public class IntroSpectorTest {

 /**
  * @param args
  */
 public static void main(String[] args) throws Exception {
  // TODO Auto-generated method stub
  ReflectPoint pt1 = new ReflectPoint(3,5);
  
  String propertyName = "x";
  //"x"-->"X"-->"getX"-->MethodGetX-->
  Object retVal = getProperty(pt1, propertyName);
  System.out.println(retVal);
  
  Object value = 7;
  
  setProperties(pt1, propertyName, value);

  System.out.println(BeanUtils.getProperty(pt1, "x").getClass().getName());
  BeanUtils.setProperty(pt1, "x", "9");
  System.out.println(pt1.getX());
  /*
  //java7的新特性
  Map map = {name:"zxx",age:18};
  BeanUtils.setProperty(map, "name", "lhm");
  */
  BeanUtils.setProperty(pt1, "birthday.time", "111");
  System.out.println(BeanUtils.getProperty(pt1, "birthday.time"));
  
  PropertyUtils.setProperty(pt1, "x", 9);
  System.out.println(PropertyUtils.getProperty(pt1, "x").getClass().getName());
  
 }

 private static void setProperties(Object pt1, String propertyName,
   Object value) throws IntrospectionException,
   IllegalAccessException, InvocationTargetException {
  PropertyDescriptor pd2 = new PropertyDescriptor(propertyName,pt1.getClass());
  Method methodSetX = pd2.getWriteMethod();
  methodSetX.invoke(pt1,value);
 }

 private static Object getProperty(Object pt1, String propertyName)
   throws IntrospectionException, IllegalAccessException,
   InvocationTargetException {
  /*PropertyDescriptor pd = new PropertyDescriptor(propertyName,pt1.getClass());
  Method methodGetX = pd.getReadMethod();
  Object retVal = methodGetX.invoke(pt1);*/
  
  BeanInfo beanInfo =  Introspector.getBeanInfo(pt1.getClass());
  PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
  Object retVal = null;
  for(PropertyDescriptor pd : pds){
   if(pd.getName().equals(propertyName))
   {
    Method methodGetX = pd.getReadMethod();
    retVal = methodGetX.invoke(pt1);
    break;
   }
  }
  return retVal;
 }

}

 

-------------------------------------XMLUtils----------------------------------------------

package cn.itcast.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

//3
public class XmlUtils {
 private static String filepath;
 static{
  filepath=XmlUtils.class.getClassLoader().getResource("users.xml").getPath();
  filepath=filepath.replace("%20", " ");
 }
 public static Document getDocument() throws Exception{
  SAXReader reader = new SAXReader();
        Document document = reader.read(new File(filepath));
        return document;
 }
 public static void write2Xml(Document document) throws Exception{
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter writer = new XMLWriter(new FileOutputStream(filepath), format );
        writer.write( document );
        writer.close();
 }

}

 

-----------------------------------------------------WebUtils-------------------------------------

package cn.itcast.utils;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

public class WebUtils {
 public static <T> T request2Bean(HttpServletRequest request,Class <T> beanClass){
  try {
   T bean = beanClass.newInstance();
   Enumeration e=request.getParameterNames();
   while(e.hasMoreElements()){
    String name=(String)e.nextElement();
    String value=request.getParameter(name);
    BeanUtils.setProperty(bean, name, value);
   }
   return bean;
  } catch (Exception e) {
   throw new RuntimeException(e);
  }
 }
 public static void copyBean(Object src,Object dest){
  /*
   private String username;
 private String password;
 private String password2;
 private String email;
 private String birthday;
 private String nickname;
 
 
  private String id; 
 private String username;
 private String password;
 private String email;
 private Date birthday;
 private String nickname;
   * */
  ConvertUtils.register(new Converter() {
   @Override
   public Object convert(Class type, Object value) {
    if (value == null)
     return null;
    String str = (String) value;
    if (str.trim().equals(""))
     return null;
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    try {
     return df.parse(str.trim());
    } catch (ParseException e) {
     throw new RuntimeException();
    }
   }
  }, Date.class);
  try {
   BeanUtils.copyProperties(dest, src);
  } catch (Exception e) {
   throw new RuntimeException();
  }
 }//产生全世界唯一的id
 public static String generateID(){  
  return UUID.randomUUID().toString();
 }

}

 

-------------------ServiceUtils--------------------------------------------

package cn.itcast.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import sun.misc.BASE64Encoder;

//8
public class ServiceUtils {

 public static String md5(String message){
  try {
   MessageDigest md=MessageDigest.getInstance("md5");
   byte md5[]=md.digest(message.getBytes());
   BASE64Encoder encoder=new BASE64Encoder();
   return encoder.encode(md5);
  } catch (NoSuchAlgorithmException e) {
   throw new RuntimeException(e);
  }
 }
}

-----------------------------------------
原创粉丝点击