jeudi 18 mars 2021

On Java, using reflect, how to tell whether a field's value is set on declaration or within a constructor body

I'm trying to tell whether a a field's value in a Java class is set on declaration or within a constructor body.

Consider the following code for Case Declaration:

class MyClass {
    int myField = 42;   // myField is initialized on declaration
    MyClass() {
        // this constructor is **not** setting myField
    }
}

versus Case Constructor:

class MyClass {
    int myField;      // myField is initialized on declaration with base value (0)
    MyClass() {
        myField = 42; // myField gets value on constructor
    }
}

Rephrasing my question: by using reflection can I tell whether I'm on Case Declaration or on Case Constructor, and if so, how?

The closest I've got is getting the field value from an instance (for example on this question) But that requires instantiation, so I finally get the value 42 in both cases.

The code for that could be something like:

public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
    Field field = MyClass.class.getDeclaredField("myField");
    MyClass instance = new MyClass();
    System.out.println("myField: " + field.get(instance));  // it writes 42 in both cases
}

I could parse both classes' source code but that would require adding some complexities to the workflow I'd rather avoid.

In case you want some context, I'm teaching an introductory course on OOP using Java, and I provide my students some JUnit code to check whether their solutions meet the requirements. In this concrete case I'm trying to force them to start using constructor's initialization for their first time.





Aucun commentaire:

Enregistrer un commentaire