Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a class with various variables

public class myClass{

    public int id;
    public String category;
    public String description;
    public String start;
    public String end;
}

Is there a way to check, either by creating an internal function or checking from the calling object, whether or not a variable exists?

E.g. To check whether myClass contains a variable called "category" (it does). Or whether it contains a category called "foo" (it does not).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
642 views
Welcome To Ask or Share your Answers For Others

1 Answer

Warning: the accepted answer will work, but it relies on exceptions as control flow, which is bad practice and should be avoided wherever possible.

Instead, consider the following alternative:

public boolean doesObjectContainField(Object object, String fieldName) {
    Class<?> objectClass = object.getClass();
    for (Field field : objectClass.getFields()) {
        if (field.getName().equals(fieldName)) {
            return true;
        }
    }
    return false;
}

Or a more succinct form using Java 8 streams:

public boolean doesObjectContainField(Object object, String fieldName) {
    return Arrays.stream(object.getClass().getFields())
            .anyMatch(f -> f.getName().equals(fieldName));
}

These code snippets do not rely on exceptions as control flow and in fact do not require any exception handling at all, which will make your implementation simpler and more readable. You would just call one of the methods above with a piece of code similar to the following:

Object someObject = ... ;
boolean fieldExists = doesObjectContainField(someObject, "foo");

As a side note, if you needed to access the private fields of your class (but not parent class fields), you could simply replace the call to getFields by getDeclaredFields.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...