views:

131

answers:

1

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?

+2  A: 

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.

Matthew Flaschen
Seems that he wants to get the *name* of the constructor, and concatenate it to the string argument of the exception...
CMS
Cool, that looks promising. But why doesn't it work with "instanceof Number"?
dcp
Not sure what `name` refers to, but it looks like it has something to do with `receiver`.
Anurag
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.
Matthew Flaschen
@Anurag - Refer to first paragraph: "assume the name variable is "receiver""
dcp
@Matthew Flaschen - LOL, is there any way to make it work for the 3 instanceof Number case, or is there some other way that can be handled?
dcp
`typeof receiver == 'number'`
Anurag
@Anurag - Yes, it seems primitives and class types have to be handled with separate cases. Thanks for your help. Thank you as well Matthew!
dcp