用fastjson对一个类进行序列化时,在没有类的实例只有类的Class的情况下,如果想知道这个Class有所有可以被序列化的字段名,可以用com.alibaba.fastjson.util.TypeUtils.computeGetters(Class<?> clazz,Map<String,String> aliasMap)
方法来实现,实现代码很简单:
package net.gdface.facelog.message;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import com.alibaba.fastjson.util.FieldInfo;
public class TestFastjson {
@Test
public void testComputeGetters(){
// 返回 Group 类所有可序列化字段信息
List<FieldInfo> fieldInfo = com.alibaba.fastjson.util.TypeUtils.computeGetters(Group.class,null);
// 输出字段名和类型
for(FieldInfo field:fieldInfo){
System.out.printf("name %s %s\n",field.name,field.fieldType.toString());
}
}
public interface Person<T>{
}
public static class User implements Person<String>{
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static class Group {
private Long id;
private String name;
private List<User> users = new ArrayList<User>();
public Date date=new Date();
public java.sql.Date sqldate=new java.sql.Date(date.getTime());
public byte[] array=new byte[]{22,33,3,2,1,5,-1};
public String nullStr=null;
private String privString="private string";
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public void addUser(User user) {
users.add(user);
}
}
}
name array class [B name date class java.util.Date name id class java.lang.Long name name class java.lang.String name nullStr class java.lang.String name sqldate class java.sql.Date name users java.util.List