Skip to content
Advertisement

How to call a method from a class given that I have the Constructor for it?

If I have a constructor object Constructor<?> productConstructor, how can I call the run() method that exists in that class?

For example, let’s say I have the class:

JavaScript

I can run the constructor for my class like this:

JavaScript
JavaScript

If I keep the code as is, then I have to place the run() method inside of the constructor to run it, but I would like the run() method outside of the constructor. How can I call my run method using the Constructor class for my class?

For example, something like this is what I had in mind but doesn’t work:

JavaScript

This doesn’t work because run is undefined. This is because I cannot call a method this way on a class that is not known until runtime. This is where my problem lies.

Advertisement

Answer

I was able to do it like this:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement