emachine emachine - 1 year ago 98
Android Question

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

Thanks for the help!

Answer Source

Your compiler usually knows that pretty well, and the runtime lets you examine loaded classes with reflection.

Object someObject = ...
Class<?> someClass = someObject.getClass();
Field someField = someClass.getField("foo");

The getField() method will throw an exception if the field can not be found.