4

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?

0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Seems that he wants to get the name of the constructor, and concatenate it to the string argument of the exception...
Cool, that looks promising. But why doesn't it work with "instanceof Number"?
Not sure what name refers to, but it looks like it has something to do with receiver.
It will work with Number. However, number literals are not instances of Number. :) 3 instanceof Number is false, but new Number(3) instanceof Number is true.
typeof receiver == 'number'
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.