0

In short: I have a method name provided via a JSON configuration file. I'd like to call a method using this provided name. The method (with a matching name) will exist in the backend. What's the best way of going about this?

I am not quite sure what I should be searching for as an example.

To detail: I am working with a legacy application, hence the VB.NET. I am building a single PDF file from multiple PDF sources. Most of these are as is, I simply read the configuration and grab the relevant files and the job is done. However some require processing, I'd like the configuration file to pass in a method name to be called that will perform extra processing on the PDF, whatever that may be.

As there can be a lot of PDF files that can vary, I cannot simply use a property such as "PostProcessing: true".

Any ideas?

  • 1
    If you don't want to just use a switch case statement, maybe look into something like this using a dictionary: https://stackoverflow.com/questions/17080219/vb-net-dictionary-of-strings-and-delegates – erastl Jan 21 '22 at 14:25

1 Answers1

1

You could use reflection to reflect method names back and check them against the name passed from the property in the config file.

Like so

    Type magicType = Type.GetType("MagicClass");
    MethodInfo magicMethod = magicType.GetMethod("ItsMagic");
    object magicValue = magicMethod.Invoke(magicClassObject, new object[]{100});

That would work.. but to be honest, I'd go with a case statement as you'll be hardcoding the method names anyway (because they are code), and it'll be strongly typed (less chance of typos and errors).

Jim
  • 479
  • 2
  • 8