Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

See if field exists in class

Tags:

java

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).

like image 488
emachine Avatar asked Sep 06 '11 19:09

emachine


People also ask

How do you see if an object exists in a list Java?

contains() method can be used to check if an element exists in an ArrayList or not. This method has a single parameter i.e. the element whose presence in the ArrayList is tested. Also it returns true if the element is present in the ArrayList and false if the element is not present.

What is Java reflection?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.


1 Answers

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.

like image 112
Pyves Avatar answered Sep 23 '22 12:09

Pyves