What you want is called introspection/reflection and it isn’t easily achieved in SystemVerilog. You can theoretically do something like this using the VPI. There are caveats however. First, your simulator vendor has to support the required parts of the VPI object model (and hopefully document them well enough, as you won’t find much on the net). Second, you’re going to have to get proficient in writing C code for this.