-1

I have a utility method which reads a value from the environment and returns a default if the property is not defined.

public String Env.getString(String name, String defaultValue);

I would like to scan the whole application (a REST microservice), on demand, to list all calls to that method. The goal is to be able to generate a dump of all the environment properties in use and the current values.

How can I use reflection (or some other scheme) to seach all classes in a given hierarchy to find calls to the utility method? As I also have getInteger, getBooleanetc an even better solution would find all methods like Env.get...

paul
  • 13,312
  • 23
  • 81
  • 144
  • it is not an easy task, can take another approach - modify this method so that it records what method has called it? – Adam Siemion Mar 18 '19 at 14:05
  • 2
    @AdamSiemion Bad advice. The job of that method is to provide a property, not to track its usage. And worse: two workloads might use different properties, so you can never be **sure** that the tracking information you receive is **complete**. – GhostCat Mar 18 '19 at 14:12
  • Would using Aspects be a viable solution? While you can't do this with reflection necessarily, you should be able to use aspectJ and define a pointcut targeting the `Env.getString` call. – Roddy of the Frozen Peas Mar 20 '19 at 15:34
  • Do you have access to the source of that application? Or at least the Jar of that application? – Tschallacka Mar 21 '19 at 10:21

1 Answers1

3

Reflection doesn't help you: that only allows you to query the structure of classes and method signatures. It does not give you access to the body of methods, thus you have no way to identify method invocations from reflection.

One solution: use a decent IDE. Eclipse or IntelliJ give you one click solutions to "find usages" for methods.

If you want something that works from the command line, you would be looking for tools that give you access to the actual bytecode. A stupid brute force way could be to use javap to disassemble all class files into text, and then grep to search within that output. More sophisticated approaches would use tools like the ASM library, see here for your usecase.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • the idea came from using eclipse as finding calls is very easy. I was hoping that eclipse uses a mechanism which I can also use at runtime. – paul Mar 18 '19 at 14:40
  • @paul IDEs spend a lot of time and energy to incorporate compiler knowledge. Basically they create an "index" where they lookup such information. Maybe there APIs to externalize that information, but I am not aware of any. But I am also not an expert in such areas. – GhostCat Mar 18 '19 at 16:02