当前位置:首页 > 服务端 > 按字符串顺序解析实体类

按字符串顺序解析实体类

package annotation;

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

/**
 * @author zhangkun
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface FieldOrder {
	int value();
}
package domain.entity;

import annotation.FieldOrder;

import java.math.BigDecimal;

public class User {
	@FieldOrder(1)
	String name;
	@FieldOrder(2)
	String id;
	@FieldOrder(3)
	Integer age;
	@FieldOrder(4)
	String sex;
	@FieldOrder(5)
	BigDecimal money;

	public BigDecimal getMoney() {
		return money;
	}

	public void setMoney(BigDecimal money) {
		this.money = money;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "User{" +
				"name='" + name + '\'' +
				", id='" + id + '\'' +
				", age=" + age +
				", sex='" + sex + '\'' +
				", money=" + money +
				'}';
	}
}
package util;

import annotation.FieldOrder;
import domain.entity.User;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangkun
 */
public class ParseUtil {
	public static <T> T parse(String s, Class<T> t) {
		try {
			T instance = t.newInstance();

			Field[] fields = t.getDeclaredFields();
			BeanInfo beanInfo = Introspector.getBeanInfo(t);
			Map<String, List<PropertyDescriptor>> propertyDescriptorsMap =
					Arrays.stream(beanInfo.getPropertyDescriptors()).collect(Collectors.groupingBy(PropertyDescriptor::getName));

			HashMap<Integer, Field> map = new HashMap<>();
			toMap(fields, map, t);

			String[] splits = s.split("\\|");
			for (int i = 0; i < splits.length; ++i) {
				String value = splits[i];

				Field field = map.get(i + 1);
				if (field == null) {
					throw new RuntimeException("split mapping field not found!");
				}


				List<PropertyDescriptor> propertyDescriptors = propertyDescriptorsMap.get(field.getName());
				if (propertyDescriptors == null || propertyDescriptors.isEmpty()) {
					throw new RuntimeException("propertyDescriptors is empty!");
				}

				PropertyDescriptor descriptor = propertyDescriptors.get(0);
				Method setMethod = descriptor.getWriteMethod();
				if (setMethod == null) {
					throw new RuntimeException(field.getName() + " set method not found!");
				}

				Class<?> propertyType = descriptor.getPropertyType();

				copyFieldValue(instance, setMethod, value, propertyType);
			}

			return instance;
		} catch (InstantiationException | IllegalAccessException |
				InvocationTargetException | IntrospectionException e) {
			e.printStackTrace();
		}
		return null;
	}

	protected static void copyFieldValue(Object obj, Method method, String value, Class<?> fieldType)
			throws InvocationTargetException, IllegalAccessException {
		String typeName = fieldType.getSimpleName();
		switch (typeName) {
			case "String":
				method.invoke(obj, value);
				break;
			case "Integer":
				method.invoke(obj, Integer.valueOf(value));
				break;
			case "BigDecimal":
				method.invoke(obj, new BigDecimal(value));
				break;
			default:
				throw new RuntimeException(typeName + " field type parser not found!");
		}
	}

	public static String toString(Object obj) {
		Class<?> aClass = obj.getClass();
		Field[] fields = aClass.getDeclaredFields();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(aClass);
			Map<String, List<PropertyDescriptor>> propertyDescriptorsMap =
					Arrays.stream(beanInfo.getPropertyDescriptors())
							.collect(Collectors.groupingBy(PropertyDescriptor::getName));

			TreeMap<Integer, Field> map = new TreeMap<>();
			toMap(fields, map, aClass);

			StringBuilder sb = new StringBuilder();
			for (Map.Entry<Integer, Field> entry : map.entrySet()) {
				Field field = entry.getValue();

				List<PropertyDescriptor> propertyDescriptors = propertyDescriptorsMap.get(field.getName());
				if (propertyDescriptors == null || propertyDescriptors.isEmpty()) {
					throw new RuntimeException("propertyDescriptors is empty!");
				}

				PropertyDescriptor descriptor = propertyDescriptors.get(0);
				Method getMethod = descriptor.getReadMethod();
				if (getMethod == null) {
					throw new RuntimeException(field.getName() + " get method not found!");
				}

				Object fieldVal = getMethod.invoke(obj);
				if (fieldVal != null) {
					sb.append(fieldVal.toString()).append("|");
				}
			}
			return sb.substring(0, sb.length() - 1);
		} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}

		return null;
	}

	public static void toMap(Field[] fields, Map<Integer, Field> map, Class<?> aClass) {
		for (Field field : fields) {
			FieldOrder annotation = field.getAnnotation(FieldOrder.class);
			if (annotation != null) {
				int order = annotation.value();
				if (map.containsKey(order)) {
					throw new RuntimeException(aClass.getSimpleName() + " FieldOrder value is repeat!");
				} else {
					map.put(order, field);
				}
			}
		}
	}

	public static void main(String[] args) {
		String s = "张三|aa|19|男|10.887";
		User user = parse(s, User.class);
		System.out.println(user);
		String userStr = toString(user);
		System.out.println(userStr);
	}
}

作者:dagger9527
来源链接:https://www.cnblogs.com/dagger9527/p/16448735.html

版权声明:
1、Java侠(https://www.javaxia.com)以学习交流为目的,由作者投稿、网友推荐和小编整理收藏优秀的IT技术及相关内容,包括但不限于文字、图片、音频、视频、软件、程序等,其均来自互联网,本站不享有版权,版权归原作者所有。

2、本站提供的内容仅用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯相关权利人及本网站的合法权利。
3、本网站内容原作者如不愿意在本网站刊登内容,请及时通知本站(javaclubcn@163.com),我们将第一时间核实后及时予以删除。





本文链接:https://www.javaxia.com/server/124895.html

分享给朋友:

“按字符串顺序解析实体类” 的相关文章

划分子网和构造超网的学习2022年05月17日 13:57:19
软件工程复习要点2022年05月17日 14:38:01
[C#]richtextbox实现拖放2022年05月17日 20:25:47
计算机组成原理考试复习2022年05月18日 15:56:51
今天,我有话说!2022年05月18日 23:15:30
centos7中 yum的安装2022年05月19日 19:54:29
Logger的级别2022年05月19日 20:04:12