I have a class with various variables
public class myClass{
public int id;
public String category;
public String description;
public String star
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
.