Java中的工具类总结七

1.Java反射工具类

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

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

/**
 * 问题:JDK5中不能传递二个可变参数,如:methodInvoke()方法
 * 
 */
public class ReflectUtils {

	/**
	 * 通过构造函数实例化对象 
	 * @param className       类的全路径名称	
	 * @param parameterTypes  参数类型
	 * @param initargs        参数值
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Object constructorNewInstance(String className,Class [] parameterTypes,Object[] initargs) { 
		try {
			Constructor<?> constructor = (Constructor<?>) Class
					.forName(className).getDeclaredConstructor(parameterTypes);					    //暴力反射
			constructor.setAccessible(true);
			return constructor.newInstance(initargs);
		} catch (Exception ex) {
			throw new RuntimeException();
		}

	}

	
	/**
	 * 暴力反射获取字段值
	 * @param fieldName 属性名
	 * @param obj       实例对象
	 * @return          属性值
	 */
	public static Object getFieldValue(String propertyName, Object obj) {
		try {
			Field field = obj.getClass().getDeclaredField(propertyName);			
			field.setAccessible(true);
			return field.get(obj);
		} catch (Exception ex) {
			throw new RuntimeException();
		}
	}
	
	/**
	 * 暴力反射获取字段值
	 * @param propertyName 属性名
	 * @param object       实例对象
	 * @return          字段值
	 */
	public static Object getProperty(String propertyName, Object object) {
		try {
			
			PropertyDescriptor pd = new PropertyDescriptor(propertyName,object.getClass());
			Method method = pd.getReadMethod();
			return method.invoke(object);
			
			//其它方式
			/*BeanInfo beanInfo =  Introspector.getBeanInfo(object.getClass());
			PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
			Object retVal = null;
			for(PropertyDescriptor pd : pds){
				if(pd.getName().equals(propertyName))
				{
					Method methodGetX = pd.getReadMethod();
					retVal = methodGetX.invoke(object);
					break;
				}
			}
			return retVal;*/
		} catch (Exception ex) {
			throw new RuntimeException();
		}
	}
	
	/**
	 * 通过BeanUtils工具包获取反射获取字段值,注意此值是以字符串形式存在的,它支持属性连缀操作:如,.对象.属性
	 * @param propertyName 属性名
	 * @param object       实例对象
	 * @return          字段值
	 */
	public static Object getBeanInfoProperty(String propertyName, Object object) {
		try {			
			return BeanUtils.getProperty(object, propertyName);
		} catch (Exception ex) {
			throw new RuntimeException();
		}
	}
	
	/**
	 * 通过BeanUtils工具包获取反射获取字段值,注意此值是以字符串形式存在的
	 * @param object       实例对象
	 * @param propertyName 属性名
	 * @param value        字段值
	 * @return          
	 */
	public static void setBeanInfoProperty(Object object,String propertyName,String value) {
		try {			
			BeanUtils.setProperty(object, propertyName,value);
		} catch (Exception ex) {
			throw new RuntimeException();
		}
	}
	
	/**
	 * 通过BeanUtils工具包获取反射获取字段值,注意此值是以对象属性的实际类型
	 * @param propertyName 属性名
	 * @param object       实例对象
	 * @return          字段值
	 */
	public static Object getPropertyUtilByName(String propertyName, Object object) {
		try {			
			return PropertyUtils.getProperty(object, propertyName);
		} catch (Exception ex) {
			throw new RuntimeException();
		}
	}
	
	/**
	 * 通过BeanUtils工具包获取反射获取字段值,注意此值是以对象属性的实际类型,这是PropertyUtils与BeanUtils的根本区别
	 * @param object       实例对象
	 * @param propertyName 属性名
	 * @param value        字段值
	 * @return          
	 */
	public static void setPropertyUtilByName(Object object,String propertyName,Object value) {
		try {			
			PropertyUtils.setProperty(object, propertyName,value);
		} catch (Exception ex) {
			throw new RuntimeException();
		}
	}
	
	/**
	 * 设置字段值	
	 * @param obj          实例对象
	 * @param propertyName 属性名
	 * @param value        新的字段值
	 * @return          
	 */
	public static void setProperties(Object object, String propertyName,Object value) throws IntrospectionException,
			IllegalAccessException, InvocationTargetException {
		PropertyDescriptor pd = new PropertyDescriptor(propertyName,object.getClass());
		Method methodSet = pd.getWriteMethod();
		methodSet.invoke(object,value);
	}
	
	
	/**
	 * 设置字段值
	 * @param propertyName 字段名
	 * @param obj          实例对象
	 * @param value        新的字段值
	 * @return          
	 */
	public static void setFieldValue(Object obj,String propertyName,Object value) {
		try {
			Field field = obj.getClass().getDeclaredField(propertyName);		
			field.setAccessible(true);
			field.set(obj, value);
		} catch (Exception ex) {
			throw new RuntimeException();
		}
	}
	
	/**
	 * 设置字段值
	 * @param className        类的全路径名称
	 * @param methodName       调用方法名
	 * @param parameterTypes   参数类型
	 * @param values           参数值
	 * @param object           实例对象
	 * @return          
	 */
	@SuppressWarnings("rawtypes")
	public static Object methodInvoke(String className,String methodName,Class [] parameterTypes,Object [] values,Object object) {
		try {
			Method method = Class.forName(className).getDeclaredMethod(methodName,parameterTypes);
			method.setAccessible(true);
			return method.invoke(object,values);
		} catch (Exception ex) {
			throw new RuntimeException();
		}
	}
}

/**
	 * @param <T> 具体对象
	 * @param fileds  要进行比较Bean对象的属性值集合(以属性值为key,属性注释为value,集合从数据库中取出)
	 * @param oldBean  源对象
	 * @param newBean  新对象
	 * @return 返回二个Bean对象属性值的异同
	 */
	public static <T> String compareBeanValue(Map<String,String> fileds,T oldBean,T newBean){
		
		StringBuilder compares = new StringBuilder();
		String propertyName = null;		
		Object oldPropertyValue = null;
		Object newPropertyValue = null;
		
		StringBuilder descrips = new StringBuilder();				
		for(Map.Entry<String, String> entity : fileds.entrySet()){
			//获取新旧二个对象对应的值
			propertyName = entity.getKey().toLowerCase();
			oldPropertyValue = getProperty(propertyName, oldBean);
			newPropertyValue = getProperty(propertyName, newBean);			
							
			if(null == oldPropertyValue && null == newPropertyValue){
				continue;
			}			
			if("".equals(oldPropertyValue) && "".equals(newPropertyValue)){
				continue;
			}			
			if(null == oldPropertyValue){
				oldPropertyValue = "";
			}			
			if(null == newPropertyValue){
				newPropertyValue = "";
			}			
			
			if(oldPropertyValue.equals(newPropertyValue)){			
				continue;
			}
			compares.append("字段注释: ").append(entity.getValue()).append("】").append("原属性值\"");
			if(StringUtils.isEmpty(oldPropertyValue+"")){
				oldPropertyValue = " ";
			}
			compares.append(oldPropertyValue).append("\"现属性值\"");
			if(StringUtils.isEmpty(newPropertyValue+"")){
				newPropertyValue = " ";
			}
			compares.append(newPropertyValue).append("\";");			
		}		
		return compares.toString();
	}


2.项目中常用工具类

package com.util;

import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.text.*;
import java.util.*;
import com.orm.Admin;


/** 工具类 */
public class Tools {
 //创建日期格式
 private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
 private static SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMdd");
 //创建中国的货币格式
 private static NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.CHINA); 

 /** FCKeditor内置的分页字符串 */
 private static String fck_separator="<div style=\"PAGE-BREAK-AFTER: always\"><span style=\"DISPLAY: none\"> </span></div>";
 
 /** 取得指定图片的宽度与高度 */
 public static Map getPicWidthHeight(String filename){
  Map map = new HashMap();
  try {
   BufferedImage sourceImg = javax.imageio.ImageIO.read(new FileInputStream(filename));
   map.put("width", sourceImg.getWidth());
   map.put("height", sourceImg.getHeight());
   return map;
  } catch (Exception e) {
   e.printStackTrace();
   return null;
  } 
 }
 
 /** 是否没有指定的操作权限 */ 
 public static boolean isDisable(Admin admin, int option) {
  if(admin==null){
   return true;
  }else{
   if (admin.getPrivilege().substring(0, 1).equals("1"))
    return false;
   else {
    if (admin.getPrivilege().substring(option - 1, option).equals("1"))
     return false;
    else
     return true;
   }   
  }
 }
 
 /** 是否拥有指定的操作权限 */ 
 public static boolean isEnable(Admin admin, int option) {
  if(admin==null){
   return false;
  }else{
   if (admin.getPrivilege().substring(0, 1).equals("1"))
    return true;
   else {
    if (admin.getPrivilege().substring(option - 1, option).equals("1"))
     return true;
    else
     return false;
   }   
  }
 }
 
 /** 取得随机主文件名 */
 public synchronized static String getRndFilename(){
  return String.valueOf(System.currentTimeMillis());
 }
 
 /** 取得指定文件的文件扩展名 */
 public synchronized static String getFileExtName(String filename){
  int p = filename.indexOf(".");
  return filename.substring(p);
 }
 
 /** 验证上传文件的类型是否合法 fileType:1-图片 2-视频*/
 public synchronized static boolean isEnableUploadType(int fileType,String filename){
  String enableExtNames = null;
  int p = filename.indexOf(".");
  String fileExtName = filename.substring(p).toLowerCase();
  if (fileType==1){//图片文件类型
   enableExtNames = ".jpg,.gif,.png";
  }else if (fileType==2){//视频文件类型
   enableExtNames = ".flv";
  }
  if (enableExtNames!=null){
   if (enableExtNames.indexOf(fileExtName)!=-1)return true;
   else return false;   
  }else{
   return true;
  }

 } 
 
 /** HTML代码的Escape处理方法 */
 public static String  escape(String src){
  int i;
  char j;
  StringBuffer tmp = new StringBuffer();
  tmp.ensureCapacity(src.length()*6);
  for (i=0;i<src.length();i++){
   j = src.charAt(i);
   if (Character.isDigit(j) || Character.isLowerCase(j) || Character.isUpperCase(j)) 
    tmp.append(j);
   else if(j<256){
    tmp.append( "%" );
    if (j<16)tmp.append("0");
    tmp.append( Integer.toString(j,16));
   }else{
    tmp.append("%u");
    tmp.append(Integer.toString(j,16));
   }
  }
  return tmp.toString();
 }
 
 /** HTML代码的UnEscape处理方法 */
 public static String  unescape(String src){
  StringBuffer tmp = new StringBuffer();
  tmp.ensureCapacity(src.length());
  int lastPos=0,pos=0;
  char ch;
  while(lastPos<src.length()){
   pos = src.indexOf("%",lastPos);
   if (pos == lastPos){
    if (src.charAt(pos+1)=='u'){
     ch = (char)Integer.parseInt(src.substring(pos+2,pos+6),16);
     tmp.append(ch);
     lastPos = pos+6;
    }else{
     ch = (char)Integer.parseInt(src.substring(pos+1,pos+3),16);
     tmp.append(ch);
     lastPos = pos+3;
    }
   }else{
    if (pos == -1){
     tmp.append(src.substring(lastPos));
     lastPos=src.length();
    }else{
     tmp.append(src.substring(lastPos,pos));
     lastPos=pos;
    }
   }
  }
  return tmp.toString();
 }
 
 /** 为以逗号分隔的字符串的每个单元加入引号,如:aa,bb-->'aa','bb' */
 public static String formatString(String src){
  StringBuffer result = new StringBuffer();
  result.append("");
  if (src!=null){
   String[] tmp = src.split(",");
   result.append("'"+tmp[0]+"'");
   for(int i=1;i<tmp.length;i++){
    result.append(",'"+tmp[i]+"'");
   }
  }  
  return result.toString();
 } 
 
    /** 截取指定字节数的字符串,且确保汉字不被拆分 */
 public static String cutString(String text, int textMaxChar){   
        int size,index;   
        String result = null;  
        if(textMaxChar<=0){   
         result= text;   
        }else{   
            for(size=0,index=0;index<text.length()&&size<textMaxChar;index++){   
                size += text.substring(index,index+1).getBytes().length;   
            }   
            result = text.substring(0,index);   
        }  
        return result;   
    }
 
    /** 按yyyy-MM-dd格式格式化日期 */
 public static String formatDate(Date date){   
  if (date==null){
   return "";
  }else{
   return df.format(date);
  }
    }
 public static String formatDate1(Date date){   
  if (date==null){
   return "";
  }else{
   return df1.format(date);
  }
    }
 
    /** 对未escape的HTML内容进行FCK分页处理,返回String[] */
 public static String[] splitContent(String unEscapedHtml){ 
  if (unEscapedHtml==null){
   return null;
  }else{
   return unescape(unEscapedHtml).split(fck_separator);
  }
 }
 
 /** 取得格式化后的中国货币字符串 */
 public static String formatCcurrency(double money){
  return currencyFormat.format(money);     

  
 }
 
 public static void main(String[] args){
  System.out.println(escape(""));
  
 }
}


3.Java反射获取泛型工具类

import java.lang.reflect.Field; 
import java.lang.reflect.Method; 
import java.lang.reflect.ParameterizedType; 
import java.lang.reflect.Type; 
import java.util.ArrayList; 
import java.util.List; 

/** 
* 泛型工具类 
*/ 
public class GenericsUtils { 
/** 
* 通过反射,获得指定类的父类的泛型参数的实际类型. 如BuyerServiceBean extends DaoSupport<Buyer> 
* 
* @param clazz 
*            clazz 需要反射的类,该类必须继承范型父类 
* @param index 
*            泛型参数所在索引,从0开始. 
* @return 范型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回 
*         <code>Object.class</code> 
*/ 
@SuppressWarnings("unchecked") 
public static Class getSuperClassGenricType(Class clazz, int index) { 
Type genType = clazz.getGenericSuperclass();// 得到泛型父类 
// 如果没有实现ParameterizedType接口,即不支持泛型,直接返回Object.class 
if (!(genType instanceof ParameterizedType)) { 
return Object.class; 
} 
// 返回表示此类型实际类型参数的Type对象的数组,数组里放的都是对应类型的Class, 如BuyerServiceBean extends 
// DaoSupport<Buyer,Contact>就返回Buyer和Contact类型 
Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); 
if (index >= params.length || index < 0) { 
throw new RuntimeException("你输入的索引" 
+ (index < 0 ? "不能小于0" : "超出了参数的总数")); 
} 
if (!(params[index] instanceof Class)) { 
return Object.class; 
} 
return (Class) params[index]; 
} 

/** 
* 通过反射,获得指定类的父类的第一个泛型参数的实际类型. 如BuyerServiceBean extends DaoSupport<Buyer> 
* 
* @param clazz 
*            clazz 需要反射的类,该类必须继承泛型父类 
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回 
*         <code>Object.class</code> 
*/ 
@SuppressWarnings("unchecked") 
public static Class getSuperClassGenricType(Class clazz) { 
return getSuperClassGenricType(clazz, 0); 
} 

/** 
* 通过反射,获得方法返回值泛型参数的实际类型. 如: public Map<String, Buyer> getNames(){} 
* 
* @param Method 
*            method 方法 
* @param int index 泛型参数所在索引,从0开始. 
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回 
*         <code>Object.class</code> 
*/ 
@SuppressWarnings("unchecked") 
public static Class getMethodGenericReturnType(Method method, int index) { 
Type returnType = method.getGenericReturnType(); 
if (returnType instanceof ParameterizedType) { 
ParameterizedType type = (ParameterizedType) returnType; 
Type[] typeArguments = type.getActualTypeArguments(); 
if (index >= typeArguments.length || index < 0) { 
throw new RuntimeException("你输入的索引" 
+ (index < 0 ? "不能小于0" : "超出了参数的总数")); 
} 
return (Class) typeArguments[index]; 
} 
return Object.class; 
} 

/** 
* 通过反射,获得方法返回值第一个泛型参数的实际类型. 如: public Map<String, Buyer> getNames(){} 
* 
* @param Method 
*            method 方法 
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回 
*         <code>Object.class</code> 
*/ 
@SuppressWarnings("unchecked") 
public static Class getMethodGenericReturnType(Method method) { 
return getMethodGenericReturnType(method, 0); 
} 

/** 
* 通过反射,获得方法输入参数第index个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, 
* Buyer> maps, List<String> names){} 
* 
* @param Method 
*            method 方法 
* @param int index 第几个输入参数 
* @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合 
*/ 
@SuppressWarnings("unchecked") 
public static List<Class> getMethodGenericParameterTypes(Method method, 
int index) { 
List<Class> results = new ArrayList<Class>(); 
Type[] genericParameterTypes = method.getGenericParameterTypes(); 
if (index >= genericParameterTypes.length || index < 0) { 
throw new RuntimeException("你输入的索引" 
+ (index < 0 ? "不能小于0" : "超出了参数的总数")); 
} 
Type genericParameterType = genericParameterTypes[index]; 
if (genericParameterType instanceof ParameterizedType) { 
ParameterizedType aType = (ParameterizedType) genericParameterType; 
Type[] parameterArgTypes = aType.getActualTypeArguments(); 
for (Type parameterArgType : parameterArgTypes) { 
Class parameterArgClass = (Class) parameterArgType; 
results.add(parameterArgClass); 
} 
return results; 
} 
return results; 
} 

/** 
* 通过反射,获得方法输入参数第一个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, Buyer> 
* maps, List<String> names){} 
* 
* @param Method 
*            method 方法 
* @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合 
*/ 
@SuppressWarnings("unchecked") 
public static List<Class> getMethodGenericParameterTypes(Method method) { 
return getMethodGenericParameterTypes(method, 0); 
} 

/** 
* 通过反射,获得Field泛型参数的实际类型. 如: public Map<String, Buyer> names; 
* 
* @param Field 
*            field 字段 
* @param int index 泛型参数所在索引,从0开始. 
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回 
*         <code>Object.class</code> 
*/ 
@SuppressWarnings("unchecked") 
public static Class getFieldGenericType(Field field, int index) { 
Type genericFieldType = field.getGenericType(); 

if (genericFieldType instanceof ParameterizedType) { 
ParameterizedType aType = (ParameterizedType) genericFieldType; 
Type[] fieldArgTypes = aType.getActualTypeArguments(); 
if (index >= fieldArgTypes.length || index < 0) { 
throw new RuntimeException("你输入的索引" 
+ (index < 0 ? "不能小于0" : "超出了参数的总数")); 
} 
return (Class) fieldArgTypes[index]; 
} 
return Object.class; 
} 

/** 
* 通过反射,获得Field泛型参数的实际类型. 如: public Map<String, Buyer> names; 
* 
* @param Field 
*            field 字段 
* @param int index 泛型参数所在索引,从0开始. 
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回 
*         <code>Object.class</code> 
*/ 
@SuppressWarnings("unchecked") 
public static Class getFieldGenericType(Field field) { 
return getFieldGenericType(field, 0); 
} 
} 


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值