1

How can I instantiate a class if all I know is its name, given the following restrictions?

  • ES6
  • The class is defined by a third-party. I have no way of knowing about the class ahead of time.

All of the answers I've seen on Stackoverflow assume that I define the class being instantiated, and as such I can create a mapping between class names and their constructions ahead of time. Example: https://stackoverflow.com/a/31790015/14731

Seeing as this cannot be done for 3rd-party classes, what can I do?

Is eval() the only way?

What I am trying to do

Users are expected to pass in a class name and I am supposed to instantiate the class, assuming the existence of a constructor that takes exactly one String argument. More specifically, I am allowing users to override the type of exception my library will throw on error.

Community
  • 1
  • 1
Gili
  • 86,244
  • 97
  • 390
  • 689
  • How do you reference the class? What information do you have available? – Alexander O'Mara Dec 28 '16 at 03:54
  • @AlexanderO'Mara Users are expected to pass in a class name and I am supposed to instantiate the class, assuming the existence of a constructor that takes exactly one `String` argument. More specifically, I am allowing users to override the type of exception my library will throw on error. – Gili Dec 28 '16 at 03:55
  • Do you have an object in which you can access that class by name? `window[inputString]` or `someObjectYouHave[inputString]` ? *"I am allowing users to override the type of exception my library will throw on error."* why not have them pass the constructor instead of a string? – Alexander O'Mara Dec 28 '16 at 03:57
  • @AlexanderO'Mara I don't think so. According to http://stackoverflow.com/a/37711826/14731 `window[className]` no longer works on ES6. And I don't see how I could have a mapping `someObjectYouHave[inputString]` for classes that I can't know about ahead of time. This mapping needs to somehow come from the system, not from my library. – Gili Dec 28 '16 at 03:59
  • The class name passed in is a string? – Trash Can Dec 28 '16 at 03:59
  • Most classes will not be directly accessible by name unless the user has explicitly exposed them as globals. Why do users need to pass a name instead of the class function itself? – loganfsmyth Dec 28 '16 at 03:59
  • *"I am allowing users to override the type of exception my library will throw on error."* Why not have them pass the constructor directly, instead of a string? – Alexander O'Mara Dec 28 '16 at 04:00
  • @loganfsmyth Good point. I came up with the same solution you mentioned (passing in a function instead of the class name) in parallel. If you post this as an answer, I'll mark it as accepted. – Gili Dec 28 '16 at 04:10

1 Answers1

0

What worked for me:

Instead of having users pass in the name of the exception they wanted to instantiate, I just had them pass in the exception constructor.

Gili
  • 86,244
  • 97
  • 390
  • 689