Spring框架基础之注解

本文介绍了一种使用自定义注解简化Java类与Map集合间数据转换的方法。通过自定义注解@Column标注字段,并利用反射技术实现类型转换,支持String、Integer等基本类型及包装类型的数据填充。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义注解并且实现一些功能

package cn.itcast.shujujiegou.StructuresAnalysis;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by likailong on 2016/9/29.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Column {
    String name();
}

package cn.itcast.shujujiegou.StructuresAnalysis;

import java.util.Date;

/**
 * Created by likailong on 2016/9/29.
 */
public class UserDo {
    @Column(name="name")
    private String userName;
    @Column(name="title")
    private String userTitle;
    @Column(name="time")
    private int loginTime;
    private int intnum;
    private String empId;
    private Date dateTime;
    public Date getDateTime() {
        return dateTime;
    }

    public void setDateTime(Date dateTime) {
        this.dateTime = dateTime;
    }

    public int getIntnum() {
        return intnum;
    }

    public void setIntnum(int intnum) {
        this.intnum = intnum;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserTitle() {
        return userTitle;
    }

    public void setUserTitle(String userTitle) {
        this.userTitle = userTitle;
    }

    public int getLoginTime() {
        return loginTime;
    }

    public void setLoginTime(int loginTime) {
        this.loginTime = loginTime;
    }

    public String getEmpId() {
        return empId;
    }

    public void setEmpId(String empId) {
        this.empId = empId;
    }
}
实现封数据方法

package cn.itcast.shujujiegou.StructuresAnalysis;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.beans.PropertyEditorManager;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
 * Created by likailong on 2016/9/29.
 * 目前对date数据不能处理 */
public class MethodBean {
    public final static SimpleDateFormat DEFAULT_DATE_FORMAT=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static <T> T converMapToBean(Map<String,String> row,Class<T> clazz) throws IllegalAccessException, InstantiationException, NoSuchMethodException, IntrospectionException, InvocationTargetException, ParseException {
        Object object=clazz.newInstance();
        List<Field> list=findFields(clazz);
        for(Field field:list){
            if(!Modifier.isStatic(field.getModifiers())&&!Modifier.isFinal(field.getModifiers())){
                if(!field.isAccessible()){
                    field.setAccessible(true);
                    Column column = field.getAnnotation(Column.class);
                    if(column!=null){
                        String value=row.get(column.name());
                        Class<?> fieldtype = field.getType();
                        if(fieldtype==String.class){
                            field.set(object,value);
                        }else if(fieldtype==Integer.class){
                            field.set(object,getInteger(value));
                        }else if(fieldtype==int.class){
                            field.setInt(object,getInt(value));
                        }else if(fieldtype==Long.class){
                            field.set(object,getLongWropper(value));
                        }else if(fieldtype==long.class){
                            field.setLong(object,getLong(value));
                        }else if(fieldtype==double.class){
                            field.set(object,getdouble(value));
                        }else if(fieldtype==Double.class){
                            field.setDouble(object,getDouble(value));
                        }
                    }else {
                        PropertyDescriptor proper=new PropertyDescriptor(field.getName(),object.getClass());
                        Method method = proper.getWriteMethod();
                        if(field.getType()==String.class){
                            method.invoke(object,row.get(field.getName()));
                        }else if(field.getType()==int.class){
                            method.invoke(object,getInt(row.get(field.getName())));
                        }else if(field.getType()==Integer.class){
                            method.invoke(object,getInteger(row.get(field.getName())));
                        }else if(field.getType()==double.class){
                            method.invoke(object,getdouble(row.get(field.getName())));
                        }else if(field.getType()==Double.class){
                            method.invoke(object,getDouble(row.get(field.getName())));
                        }else if(field.getType()==Date.class){
                            method.invoke(object,getDates(row.get(field.getName())));
                        }
                        else {
                           //这是解决注入问题
                            PropertyEditor properEditor= PropertyEditorManager.findEditor(field.getType());
                            if(properEditor!=null){
                                properEditor.setAsText(row.get(field.getName()));
                                method.invoke(object,properEditor.getValue());
                            }else {
                                System.out.println("----------------");
                            }
                        }
                    }
                }
            }
        }
        return (T)object;
    }

    private static Date getDates(String s) throws ParseException {
          return  DEFAULT_DATE_FORMAT.parse(s);
    }

    private  static Double getDouble(String value){
        return Double.parseDouble(value);
    }
    private  static double getdouble(String value){
        return Double.parseDouble(value);
    }
    private static int getInt(String value){
         return Integer.valueOf(value);
     }
    private static Integer getInteger(String value){
        return Integer.parseInt(value);

    }
    private static long getLongWropper(String value){
      return Long.parseLong(value);
    }
    private static Long getLong(String value){
        return Long.parseLong(value);
    }
    private static <T> List<Field> findFields(Class<T> clazz) {
        Field[] aa = clazz.getDeclaredFields();
        List<Field> list=new LinkedList<>();
        for(Field field:aa){
            list.add(field);
        }
        return list;
    }
}
test方法

package cn.itcast.shujujiegou.StructuresAnalysis;

import cn.itcast.shujujiegou.Jdbc.JdbcUtils;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * Created by likailong on 2016/9/29.
 */
public class TestBeanMian {
    public static void main(String [] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, IntrospectionException, InvocationTargetException, ParseException, SQLException {
        List<HashMap<String,String>>list= Arrays.asList(
                new HashMap<String, String>(){
                    {
                        put("name","xieyuoo");
                        put("title","李凯龙");
                        put("time","4");
                        put("empId","123456");
                        put("intnum","12");
                        put("dateTime","2016-12-21 12:21:12");
                    }
                },
                new HashMap<String, String>(){
                    {
                        put("name","ffff");
                        put("title","标题");
                        put("time","6");
                        put("empId","1234567");
                        put("intnum","15");
                        put("dateTime","2016-12-21 12:21:12");
                    }
                }
        );
        List<UserDo> users=new ArrayList<>(list.size());
        for(HashMap<String,String> row:list){
            users.add(MethodBean.converMapToBean(row,UserDo.class));
        }
        for(UserDo userDo:users){
            System.out.println(userDo.getUserName()+"--------"+userDo.getUserTitle()+"----"+userDo.getLoginTime()+"--"+userDo.getEmpId());
        }
       // JdbcUtils.getConnection();
    }
}

结果展示


展示




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值