主函数:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.google.common.base.Preconditions;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class leijun {public static void main(String[] args) {A a = new A();B b1 =ObjectUtils.mapObject(B.class,a);System.out.println(b1.a);System.out.println(b1.des);System.out.println(b1.desdep);} }
通过反射来转换的代码:
class ObjectUtils {public static <T> T mapObject(Class<T> clazz, Object o){Preconditions.checkNotNull(clazz);Preconditions.checkNotNull(o);String json = JSON.toJSONString(o);T res = JSON.parseObject(json, clazz);return res;} }
实体:
class A{int a=1;int b=1;String des ="wuhan";String dep ="xiantao";public String getDes() {return des;}public void setDes(String des) {this.des = des;}public String getDep() {return dep;}public void setDep(String dep) {this.dep = dep;}public int getA() {return a;}public void setA(int a) {this.a = a;}public int getB() {return b;}public void setB(int b) {this.b = b;} }
class B{int a;String desdep;String des;String dep;public String getDesdep() {return desdep;}public void setDesdep(String desdep) {this.desdep = desdep;}public int getA() {return a;}public void setA(int a) {this.a = a;}public String getDep() {return dep;}public void setDep(String dep) {this.dep = dep;}public String getDes() {return des;}public void setDes(String des) {this.des = des; }}
运行结果为:
1
wuhan
null
Process finished with exit code 0
总结:A类里多的属性不会赋值到B里,B里多的属性会变味默认值。