How to check if given class has specific field and if it is initialized (has value at the moment)?
abstract class Player extends GameCahracter {
}
public class Monster extends GameCahracter{
public int level = 1;
}
abstract class GameCharacter{
public void attack(GameCahracter opponent){
if (opponent instanceof Monster && ){ // << here I have to know is it instance of Monster and if it has initialized value
}
}
In JavaSW, it's easy to list the declared fields of a class. If you have an object, you can obtain its Class object by calling getClass() on the object. You can then call getDeclaredFields() on the Class object, which will return an array of Field objects. This list can include public, protected, and private fields.
To see if a class has a property without rely on exception, you can use these methods:
private Boolean objectHasProperty(Object obj, String propertyName){
List<Field> properties = getAllFields(obj);
for(Field field : properties){
if(field.getName().equalsIgnoreCase(propertyName)){
return true;
}
}
return false;
}
private static List<Field> getAllFields(Object obj){
List<Field> fields = new ArrayList<Field>();
getAllFieldsRecursive(fields, obj.getClass());
return fields;
}
private static List<Field> getAllFieldsRecursive(List<Field> fields, Class<?> type) {
for (Field field: type.getDeclaredFields()) {
fields.add(field);
}
if (type.getSuperclass() != null) {
fields = getAllFieldsRecursive(fields, type.getSuperclass());
}
return fields;
}
And simply call:
objectHasProperty(objInstance, "myPropertyName");
In fact does not matter the instance of the class to see if the class has the property, but I made that way, just to be little more friendly. Just to conclude: I made the getAllFields to be recursive, to get all the superclasses methods too (in my case this is important)
After that, if you want to see what is the value of the property in the desired object, you can just call:
PropertyUtils.getProperty(objInstance, "myPropertyName");
Remember: if objInstance
does not have that property, the call above will throw NoSuchMethodException
(That is why you need to use the fist code to see if the class has the property)
You can use reflection, for example like this:
Class.forName("Foo").getFields()
And then you can check again if particular object has this field initialiazed by using reflection.
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