Reflection: how to get the value of a field without evaluation?

Playing with java.lang.reflect

and wondering if there is any way to get the assignment valuejava.lang.reflect.Field

Example

public class Dummy {
    String envHttpPort = System.getenv("HTTP_PORT");
}

      

From java reflection, I would like to return a value System.getenv("HTTP_PORT");

instead of null

what it seems to be by instantiating the class that I know is required to get the field values ​​would be the value of the call to System.getenv (String), which I don't want.

Can field and value be read as?

The required output will be the same as the original code.

I hope you guys can understand if you don’t tell me and I will try to rephrase the question.

+3


source to share


1 answer


No, it is not possible to get the "assignment value" of a field (since you arbitrarily defined it for the purposes of this question), since, as you already saw, it is not a value, it is a piece of code.

This code is part of the initialization of the instance and cannot be retrieved without bytecode manipulation. Even though it can be retrieved, it will only know how to set the value of a specific field to a specific class, it will not return any value that you can use. It will also very likely call other code in the class to do its work, so even if you managed to isolate it somehow, it would be impossible to execute it outside of normal instance initialization.



In short, don't even think about it.

0


source







All Articles