数据传输格式:json 与 xml 与反射机制

数据传输格式:json 与 xml 与反射机制
2020年12月04日 11:15 拉勾IT培训

  • 一、数据格式1.JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,主要用于restful接口返回数据。---拉勾IT课小编为大家分解2.xml主要用于一些老项目,用xml报文提交数据,返回数据;但是通常拿到数据还是会转成json数据传给前端。

  • 3.json的解析工具fastjson,gson,net.sf.json(用),jackSon;xml的解析工具dom4j(实际用)、xpath(mybaties底层解析mapper.xml用的);

  • 二、反射机制

public class TestRefect {

public static void main(String[] args){

//获取对象

try {

Class>clazz = Class.forName("com.myrefecct.UserEntity");

//1.使用UserEntity的无参构造创建

UserEntity userEntity = (UserEntity) clazz.newInstance();

//判断空

String userName = Optional.ofNullable(userEntity).map(obj->{

obj.setUserName("白酒");

return obj;

}).isPresent() ? userEntity.getUserName() : "";

System.out.println("用户名:"+userName);

System.out.println("======================华丽分隔线=====================================");

//2.有参构造的使用,参数列表,按顺序

Constructor userCons = clazz.getConstructor(String.class,String.class);

//使用有参构造

UserEntity userEntity1 = (UserEntity) userCons.newInstance("1","诺安成长混合");

String usrName = Optional.ofNullable(userEntity1).isPresent() ? userEntity1.getUserName():"";

System.out.println("用户名2:"+usrName);

System.out.println("======================华丽分隔线=====================================");

//3.获取所有成员属性,

Field[] fields = clazz.getDeclaredFields();

Arrays.stream(fields).forEach(field -> System.out.println("字段名:"+field.getName()+",字段类型:"+field.getType()));

System.out.println("======================华丽分隔线=====================================");

//获取该类的所有方法

Method[] methods = clazz.getDeclaredMethods();

Arrays.stream(methods).forEach(method -> System.out.println("方法名:"+method.getName()+",返回类型:"+method.getReturnType()));

}catch (Exception e){

e.printStackTrace();

}

}

}

public class UserEntity {

private String id;

private String userName;

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

public UserEntity(String id, String userName) {

this.id = id;

this.userName = userName;

}

public UserEntity() {

}

}

财经自媒体联盟更多自媒体作者

新浪首页 语音播报 相关新闻 返回顶部