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).
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With