Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a given class has a field and it was initialized?

Tags:

java

oop

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
           }
}
like image 910
J.Olufsen Avatar asked Apr 14 '12 19:04

J.Olufsen


People also ask

How do you find the declared field of a class?

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.


2 Answers

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)

like image 116
Renato Lochetti Avatar answered Sep 27 '22 23:09

Renato Lochetti


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.

like image 25
hgrey Avatar answered Sep 27 '22 21:09

hgrey