All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sghd.logging.csv.CsvInfo Maven / Gradle / Ivy

The newest version!
package com.sghd.logging.csv;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Comparator;

import com.sghd.common.utils.json.JsonUtils;

/**
 * CSV记录访问器
 * @author solq
 */
public class CsvInfo {

	public static final Comparator ASC = new Comparator() {

		@Override
		public int compare(CsvInfo o1, CsvInfo o2) {
			return o1.getIndex() < o2.getIndex() ? -1 : 1;
		}
	};

	private int index;
	private Method method;
	private Field field;

	public static CsvInfo valueOf(int index, Method method, Field field) {
		CsvInfo result = new CsvInfo();
		result.index = index;
		result.method = method;
		result.field = field;
		return result;
	}

	public Object getValue(Object obj) {
		Object value = null;
		try {
			if (field != null) {
				value = field.get(obj);
			} else {
				value = method.invoke(obj);
			}

		} catch (Exception e) {
			throw new RuntimeException("CSV解释错误", e);
		}
		if (value != null) {
			value = String.valueOf(value).trim();
			if (value.equals("")) {
				return null;
			}
		}
		return value;
	}

	public void injectValue(Object obj, String value) {
		try {
			if (field != null) {
				Type type = field.getGenericType();
				Object nvalue = JsonUtils.string2Object(value, type);
				field.set(obj, nvalue);
			}
		} catch (Exception e) {
			throw new RuntimeException("CSV赋值错误", e);
		}
	}

	// get
	public int getIndex() {
		return index;
	}

	public Field getField() {
		return field;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + index;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		CsvInfo other = (CsvInfo) obj;
		if (index != other.index)
			return false;
		return true;
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy