dcp
dcp

Reputation: 55444

javascript instanceof get type from string name

Let's say I have this (assume the name variable is "receiver"):

if (!(receiver instanceof com.HTMLReceiver)) {
    throw new com.IllegalArgumentException(
        name + " is not an instance of com.HTMLReceiver.");
}

I'd like to factor this code out into a common method so I could call it like this:

Helper.checkInstance(receiver, "com.HTMLReceiver");

But I don't know of a way to convert the com.HTMLReceiver from a string to its actual type so I can use instanceof on it.

Is there a way?

Upvotes: 4

Views: 1038

Answers (1)

Matthew Flaschen
Matthew Flaschen

Reputation: 284806

I would call it as:

Helper.checkInstance(receiver, com.HTMLReceiver);

This will not allow you print a type name ("com.HTMLReceiver").

or:

Helper.checkInstance(receiver, com.HTMLReceiver, "com.HTMLReceiver");

You use the user string in the print.

Note that the same type can have multiple type names

var foo = com.HTMLReceiver;

foo and com.HTMLReceiver are names for the same thing.

JavaScript has no way of going from type to type name itself.

If you only pass in the String, I think the only general solution is eval.

Upvotes: 3

Related Questions