How to determine the number of fields set on an object in Java

I'm not sure if I can do this, but I say I have this object:

public class SomeObject
{
    private String field1;
    private String field2;
    ....

    //Blah Blah getters and setters for all fields
}

I want to know how many of these fields are not empty My specific object has 40 fields, so I really don't want the if block to check each of the 40 fields separately I thought I could do this with reflection in some way? But I really don't know what I'm doing Just walk through all the fields and check their values

For the people there, I don't think it's easy

Solution

Yes, you can do this with reflection:

SomeObject objectReference = ...; // The object you're interested in
Class clazz = SomeObject.class;
int nullCount = 0;
for (Field field : clazz.getDeclaredFields())
{
    field.setAccessible(true);
    if (field.get(objectReference) == null)
    {
        nullCount++;
    }
}

(except for various exceptions, permissions, etc.)

It feels a bit like a hacker... To be honest, it's a bit strange You definitely need all 40 fields. Do you need to treat them as separate fields instead of (for example) arrays?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>