Java获取类或对象中的字段名称和JsonProperty注释的名称

创建一个模型如下:

package model;

import com.fasterxml.jackson.annotation.JsonProperty;

public class ProvNode
{
    @JsonProperty("machineId")
    private String nodeId;

    private String name;

    private String result;

    private String status;

    @JsonProperty("message")
    private String msg;

    @JsonProperty("privateIpAddress")
    private String privateIpAddr;

    @JsonProperty("publicIpAddress")
    private String publicIpAddr;

    @JsonProperty("launchtime")
    private Long launchTime;

    public String getNodeId()
    {
        return nodeId;
    }

    public void setNodeId(String nodeId)
    {
        this.nodeId = nodeId;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String getResult()
    {
        return result;
    }

    public void setResult(String result)
    {
        this.result = result;
    }

    public String getStatus()
    {
        return status;
    }

    public void setStatus(String status)
    {
        this.status = status;
    }

    public String getMsg()
    {
        return msg;
    }

    public void setMsg(String msg)
    {
        this.msg = msg;
    }

    public String getPrivateIpAddr()
    {
        return privateIpAddr;
    }

    public void setPrivateIpAddr(String privateIpAddr)
    {
        this.privateIpAddr = privateIpAddr;
    }

    public String getPublicIpAddr()
    {
        return publicIpAddr;
    }

    public void setPublicIpAddr(String publicIpAddr)
    {
        this.publicIpAddr = publicIpAddr;
    }

    public Long getLaunchTime()
    {
        return launchTime;
    }

    public void setLaunchTime(Long launchTime)
    {
        this.launchTime = launchTime;
    }
}

创建一个Test类:

import java.lang.reflect.Field;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.ibm.spectrum.prov.model.ProvNode;

public class Test
{

    public static void main(String[] args)
    {
        for (Field field : ProvNode.class.getDeclaredFields())
        {
            JsonProperty annotation = field.getAnnotation(JsonProperty.class);
            if (null == annotation)
            {
                System.out.println(field.getName());
                continue;
            }
            System.out.println(annotation.value());
        }
    }
}

结果如下:

machineId
name
result
status
message
privateIpAddress
publicIpAddress
launchtime

转载于:https://www.cnblogs.com/wisdom-projects/p/11162003.html

你可能感兴趣的:(Java获取类或对象中的字段名称和JsonProperty注释的名称)