Java Reflection访问公共字段

时间:2019-04-01 16:37:51

标签: java reflection

我正在为List类编写自定义序列化程序(Jackson JSON),可以使用不同的类类型来推断此列表,因此我需要使用反射来获取对象字段值。

请注意,所有此类均具有公共值(没有设置器和获取器),因此,调用获取器将不是一种选择。

这是我到目前为止得到的:

package com.xxx.commons.my.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.List;

public class ListSerializer extends StdSerializer<List> {

public ListSerializer() {
    super(List.class);
}

@Override
public void serialize(List aList, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {

    if (aList != null) {

        jsonGenerator.writeStartObject();

        for (int index = 0 ; index < aList.size(); index++) {

            try {

                Object next = aList.get(index);

                List<Field> fields = FieldUtils.getAllFieldsList(next.getClass());

                Object object = next.getClass().newInstance();

                for (int j = 0 ; j < fields.size(); j ++ ) {

                    jsonGenerator.writeObjectField(String.format("%s[%s]",fields.get(j).getName(),index) , object);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        jsonGenerator.writeEndObject();
    }
}
}

MyTest

package com.xxx.commons.my.serializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.junit.Test;

public class ListSerializerTest {

    private ObjectMapper mapper = new ObjectMapper();

    @Test
    public void test() throws Exception {

        SimpleModule module = new SimpleModule();

        module.addSerializer(new ListSerializer());

        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        mapper.registerModule(module);

        MyTempClassParent parent = new MyTempClassParent();
        parent.mylist.add(new MyTempClass("1","2","3"));

        String json = mapper.writeValueAsString(parent);

        System.out.println(json);
    }   

}

示例类:

public class MyTempClass {

    public MyTempClass() {
    }

    public MyTempClass(String value1, String value2, String value3) {
        this.valueA = value1;
        this.valueB = value2;
        this.valueC = value3;
    }

    public String valueA;
    public String valueB;
    public String valueC;
}

public class MyTempClassParent {

   public List<MyTempClass> mylist = new LinkedList<>();
}

撰写此书的任何想法或替代方法吗?

1 个答案:

答案 0 :(得分:0)

也许您应该只将ObjectMapper与设置属性访问器一起使用才能访问每个字段:

ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

    MyDtoAccessLevel dtoObject = new MyDtoAccessLevel();

    String dtoAsString = mapper.writeValueAsString(Arrays.asList(dtoObject));
    System.out.println(dtoAsString);

结果: [{“ stringValue”:null,“ intValue”:0,“ floatValue”:0.0,“ booleanValue”:false}] dto:

class MyDtoAccessLevel {
    private String stringValue;
    int intValue;
    protected float floatValue;
    public boolean booleanValue;
    // NO setters or getters

-编辑 为了通过反射从对象获取值:

    @Override
public void serialize(List aList, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {

    if (aList != null) {

        jsonGenerator.writeStartObject();

        for (int index = 0 ; index < aList.size(); index++) {

            try {

                Object next = aList.get(index);

                List<Field> fields = FieldUtils.getAllFieldsList(next.getClass());

                for (int j = 0 ; j < fields.size(); j ++ ) {

                    jsonGenerator.writeObjectField(String.format("%s[%s]",fields.get(j).getName(),index) , fields.get(j).get(next));
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        jsonGenerator.writeEndObject();
    }
}

请在问题中写下您要在输出中包含什么内容。