java bean to map_JavaBean转换成Map(配合注解实现属性过滤)

1、首先编写一个注解类,用于标注在字段或者方法上,实现属性的过滤

package com.renyiwei.wydns.annotation;

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)

// 可以注解在方法或者字段上

@Target({ ElementType.FIELD, ElementType.METHOD })

public @interface ToMapIgnore {

boolean Value() default true;

}

2、编写工具类,实现对象到map的转化(该工具还没有完成读取get方法上的注解)

package com.renyiwei.wydns.utils;

import java.lang.reflect.Field;

import java.util.HashMap;

import java.util.Map;

import com.renyiwei.wydns.annotation.ToMapIgnore;

public class CommonUtil {

public static MaptoMap(Object bean) throws IllegalArgumentException, IllegalAccessException {

MapreturnMap = new HashMap();

Field[] fields = bean.getClass().getDeclaredFields();

for (Field field : fields) {

//获取该字段的注解

ToMapIgnore annotation = field.getAnnotation(ToMapIgnore.class);

//如果没有注解 或者 注解值为false 则获取该值存入返回的map中

if (annotation == null || !annotation.Value()) {

field.setAccessible(true);

returnMap.put(field.getName(), field.get(bean));

}

}

return returnMap;

}

}

3、实例:如果不想转化对象中的module属性,则在起字段上进行注解 @ToMapIgnore既可以

package com.renyiwei.wydns.domain;

import com.renyiwei.wydns.annotation.ToMapIgnore;

public class Server {

private Long id;

private String name;

private String apiurl;

private String username;

private String password;

//在这里进行注解

@ToMapIgnore

private Module module;

//省略get set方法

}

4、调用

MapserverMap = CommonUtil.toMap(product.getServer());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值