將請求(ServletHttpRequest)中的數據注入到對象中返回

package com.yc.refection.utils;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


import javax.servlet.http.HttpServletRequest;


public class RefectionUtil{
@SuppressWarnings({ "unchecked" })
public static <T> T getObjectFormRequest(HttpServletRequest request,Class<T> c) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException{
List<Method> list=getSetMethods(c); //獲取要注入的類的所有公有setter方法
Enumeration<String> enums=request.getParameterNames();


T t=c.newInstance(); //獲取注入類的一個實例


String key; //request中的請求參數名


Map<String,Map<String,Integer>> arrObject=new HashMap<String,Map<String,Integer>>(); 


String[] splitArr;


Map<String,Integer> mp;


//循環所有的屬性名,並取出所有的屬性值
while(enums.hasMoreElements()){
key=enums.nextElement();


if(key.indexOf(".")>0 && key.indexOf("[")<0){
List<String> splitStr=mySplist(key);
for(int i=0;i<splitStr.size()-1;i++){ //循環獲取屬性
t=(T) getObject(splitStr.get(i),splitStr.get(i+1),c,t,request);
}
}else if(key.indexOf("[")>0){ //數組存儲   //start[0].name
splitArr=getSplitKey(key);
//判斷map是否存在這個鍵
if(arrObject.containsKey(splitArr[0])){
mp=arrObject.get(splitArr[0]);
}else{
mp=new HashMap<String,Integer>();
}
if( mp.containsKey(splitArr[2]) ){
mp.put(splitArr[2],mp.get(splitArr[2])+1);
}else{
mp.put(splitArr[2],1);
}
arrObject.put(splitArr[0],mp);
}else{
t=(T)setDirectInjection(list,key,request,t);
}
}


//star[0].name分割的數組
if(arrObject!=null && arrObject.size()>0){
t=(T) getObjects(arrObject,c,t,request);
}
return t;
}


@SuppressWarnings("unchecked")
public static <T> Object getObjects(Map<String,Map<String,Integer>> arrObject,Class<T> c,Object t,HttpServletRequest request) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException, ClassNotFoundException{
Set<String> keys=arrObject.keySet();
List<Method> getMethods=getGetMethods(c); //獲取當前類中所有公用的get方法


Object subObject=null;
Type type=null;
String typeName=null;
List<T> list=null;
Class<T> cl;
T myObject; //實例對象
Map<String,Integer> attrInfo;
Set<String> innerKey;


for(String key:keys){
for(Method md:getMethods){
if(("get"+getChangeName(key)).equals(md.getName())){
subObject=md.invoke(t,null); //獲取當前注入對象事否爲空


if(subObject==null){//如果爲空,初始化一個對象出來,然後調用set方法注入
for(Method setMd:getSetMethods(c)){
if(("set"+getChangeName(key)).equals(setMd.getName())){
type=getMethodType(setMd);
typeName=type.toString().replaceFirst("^(class\\s*)","");


if(type instanceof ParameterizedType){//判斷type 是不是參數化類型。 如Collection<String>就是一個參數化類型。
if(typeName.startsWith("java.util.List")){
list=new ArrayList<T>();

type=((ParameterizedType)type).getActualTypeArguments()[0];
typeName=type.toString().replaceFirst("^(class\\s*)","");


//獲取一個類的實例化
cl=(Class<T>) Class.forName(typeName);
attrInfo=arrObject.get(key);

innerKey=attrInfo.keySet();

for(int i=0;i<attrInfo.get(innerKey.toArray()[0]);i++){
myObject=(T)cl.newInstance();
for(String s:innerKey){
myObject=(T)setDirectInjections(getSetMethods(myObject.getClass()),key+"["+i+"]."+s,request,myObject);
}
list.add( myObject );
}
}
}
subObject=setMd.invoke(t,list); 
break;
}
}
}
}
}
}
return t;
}




@SuppressWarnings("unused")
public static <T> Object getObject(String name,String nextName,Class<T> c,Object t,HttpServletRequest request) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException{
List<Method> getMethods=getGetMethods(c); //獲取當前類中所有公用的get方法
Object subObject=null;


List<Method> setMethods=null; //嵌套類的setter方法集合


for(Method md:getMethods){
if(("get"+getChangeName(name)).equals(md.getName())){
subObject=md.invoke(t,null); //獲取當前注入對象事否爲空
if(subObject==null){//如果爲空,初始化一個對象出來,然後調用set方法注入
for(Method setMd:getSetMethods(c)){
if(("set"+getChangeName(name)).equals(setMd.getName())){
subObject=md.getReturnType().newInstance();
setMd.invoke(t,subObject); 
break;
}
}
}
subObject=(T)setDirectInjections(getSetMethods(subObject.getClass()),name+"."+nextName,request,subObject);
break;
}
}
return t;
}


/**
* 將給定的屬性名的第一個字母變成大寫
* @param name:轉換後的字符
* @return
*/
public static String getChangeName(String name){
return name.substring(0,1).toUpperCase()+name.substring(1);
}


/**
* 將字符串爲star[0].name分割成一個數組
* @param key:要分割的字符串
* @return:分割後的數組
*/
public static String[] getSplitKey(String key){
String[] str=new String[3];
str[0]=key.substring(0,key.indexOf("["));
str[1]=key.substring(key.indexOf("[")+1,key.indexOf("]"));
str[2]=key.substring(key.indexOf("]")+2);
return str;
}


/**
* 根據.將字符串分割成數組
* @param str:要分割的字符串
* @return:分割好的集合
*/
public static List<String> mySplist(String str){
List<String> list=new ArrayList<String>();
String temp;
while(!"".equals(str)&&str.indexOf(".")>0){
temp=str.substring(0,str.indexOf("."));
list.add(temp);
str=str.substring(str.indexOf(".")+1);
}
list.add(str);
return list;
}


/**
* 普通類型注值
* @param method:要反向激活的方法
* @param request:當前請求
* @param typeName:參數類型
* @param key:取值屬性
* @param t:要注入到的對象
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static Object setDirectInjection(List<Method> list,String key,HttpServletRequest request,Object t) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{
Type type=null; //參數類型名
String typeName=null;
Object[] str;


//循環匹配所有的setter方法
for(Method method:list){
if(("set"+getChangeName(key)).equals(method.getName())){ //如果找到了對應的方法
//取出該方法的參數類型
type=getMethodType(method);
typeName=type.toString().replaceFirst("^(class\\s*)","");


if(type instanceof ParameterizedType){//判斷type 是不是參數化類型。 如Collection<String>就是一個參數化類型。
if(typeName.startsWith("java.util.List")){
//獲取List中的參數類型
type=((ParameterizedType)type).getActualTypeArguments()[0];
str=(Object[]) request.getParameterValues(key);
List<Object> params=Arrays.asList(str);
method.invoke(t,params);
}
}else{
t=setDirectInjectionType(method,request,typeName,key,t);
}
break;
}
}
return t;
}


/**
* 帶一個.的注值
* @param method:要反向激活的方法
* @param request:當前請求
* @param typeName:參數類型
* @param key:取值屬性
* @param t:要注入到的對象
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static Object setDirectInjections(List<Method> list,String key,HttpServletRequest request,Object t) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{
Type type=null; //參數類型名
String typeName=null;
Object[] str;
String name=key;


//循環匹配所有的setter方法
for(Method method:list){
if(key.indexOf("]")>0){
name=key.substring(key.lastIndexOf("]")+2);
}else if(key.indexOf(".")>0){
name=key.substring(key.lastIndexOf(".")+1);
}


if(("set"+getChangeName(name)).equals(method.getName())){ //如果找到了對應的方法
//取出該方法的參數類型
type=getMethodType(method);
typeName=type.toString().replaceFirst("^(class\\s*)","");


if(type instanceof ParameterizedType){//判斷type 是不是參數化類型。 如Collection<String>就是一個參數化類型。
if(typeName.startsWith("java.util.List")){
//獲取List中的參數類型
type=((ParameterizedType)type).getActualTypeArguments()[0];
str=(Object[]) request.getParameterValues(key);
List<Object> params=Arrays.asList(str);
method.invoke(t,params);
}
}else{
t=setDirectInjectionType(method,request,typeName,key,t);
}
break;
}
}
return t;
}


/**
* 普通類型注值
* @param method:要反向激活的方法
* @param request:當前請求
* @param typeName:參數類型
* @param key:取值屬性
* @param t:要注入到的對象
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static Object setDirectInjectionType(Method method,HttpServletRequest request,String typeName,String key,Object t) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{
if("java.lang.String".equals(typeName)){
method.invoke(t,request.getParameter(key));
}else if("int".equals(typeName)){
method.invoke(t,Integer.parseInt(request.getParameter(key)));
}else if("double".equals(typeName)){
method.invoke(t,Double.parseDouble(request.getParameter(key)));
}else if("float".equals(typeName)){
method.invoke(t,Float.parseFloat(request.getParameter(key)));
}else if("boolean".equals(typeName)){
method.invoke(t,Boolean.parseBoolean(request.getParameter(key)));
}else{
method.invoke(t,request.getParameter(key));
}
return t;
}




/**
* 獲取給定類的所有公有的setter方法
* 包括那些由該類或接口聲明的以及從超類和超接口繼承的那些的類或接口
* @param cl:要獲取的類
* @return:該類的所有公有的setter方法集合
*/
public static <T> List<Method> getSetMethods(Class<T> cl){
List<Method> list=new ArrayList<Method>();


//返回一個包含某些 Method 對象的數組,這些對象反映此 Class 對象所表示的類或接口(包括那些由該類或接口聲明的以及從超類和超接口繼承的那些的類或接口)的公共 member 方法。
Method[] methods=cl.getMethods();
for(Method method:methods){
if(method.getName().startsWith("set")){
list.add(method);
getMethodType(method);
}
}
return list;
}


/**
* 獲取給定類的所有公有的getter方法
* 包括那些由該類或接口聲明的以及從超類和超接口繼承的那些的類或接口
* @param cl:要獲取的類
* @return:該類的所有公有的getter方法集合
*/
public static <T> List<Method> getGetMethods(Class<T> cl){
List<Method> list=new ArrayList<Method>();


//返回一個包含某些 Method 對象的數組,這些對象反映此 Class 對象所表示的類或接口(包括那些由該類或接口聲明的以及從超類和超接口繼承的那些的類或接口)的公共 member 方法。
Method[] methods=cl.getMethods();
for(Method method:methods){
if(method.getName().startsWith("get")){
list.add(method);
}
}
return list;
}


/**
* 獲取給定方法的第一個參數的參數類型
* @param method:要獲取第一個參數的方法
* @return:該方法第一個參數的參數類型
*/
public static Class<?> getMethodClass(Method method){
Class<?>[] cls=method.getParameterTypes();
if(cls!=null&&cls.length>0){
return cls[0];
}
return null;
}


/**
* 獲取給定方法的第一個參數的參數類型
* @param method:要獲取第一個參數的方法
* @return:該方法第一個參數的參數類型
*/
public static Type getMethodType(Method method){
Type[] type=method.getGenericParameterTypes();
if(type!=null&&type.length>0){
return type[0];
}
return null;
}
}
發佈了70 篇原創文章 · 獲贊 78 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章