Java工具:反射处理对象属性做0处理

package com.zycfc.vps.kpi.provider.util;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import com.zycfc.vps.core.base.orm.homepage.keyday.po.TVpsHomepageKeyDayPo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Data
public class TransZeroUtils {
	public int sum;
	public static void setFieldValue(Object obj,String classType,String value)  {
		try {
			Field f = obj.getClass().getDeclaredField(classType);
			if(f==null) {
				return;
			}
			f.setAccessible(true);
			if(f.getType()==BigDecimal.class) {
				BigDecimal o =(BigDecimal) f.get(obj);
				if(o.signum()==-1) {
				    f.set(obj, new BigDecimal(value));
				}
			    return;
			}
			if(f.getType()==String.class) {
				String o=(String)f.get(obj);
				if(Integer.valueOf(0)<=0) {
				    f.set(obj, value);
				}
			    return;
			}
			if(f.getType()==Integer.class) {
				Integer o=(Integer)f.get(obj);
				if(o<=0) {
					f.set(obj, Integer.valueOf(value));
				}		    
			    return;
			}
			if(f.getType()==int.class) {
				int o=(int)f.get(obj);
				if(o<=0) {
					f.set(obj, Integer.valueOf(value));
				}		    
			    return;
			}
			
		} catch (Exception e) {
			log.error("转化错误",e);
		}
					        
	}
	public static void main(String[] args) {
		TransZeroUtils t=new TransZeroUtils();
		t.setSum(-20);
		System.out.println(t);		
		setFieldValue(t,"sum","0");
		System.out.println(t);
		
	}
}

 

你可能感兴趣的:(工具类)