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

java, oop

Solution

//Load the class 

Class clazz = Class.forName("your.class.ClassName");
Field field = clazz.getField("fieldName")
if(field!=null){
 //field exist now check if its initialized or not, or if its primitive field check against its assumed initialized value
 if(ClassName.fieldName!=null){
    //yes initilized
 }
}

Problem

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 } } ```

Original source