Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

java - See if field exists in class

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...