javascript instanceof 从字符串名称获取类型
假设我有这个(假设名称变量是“receiver”):
if (!(receiver instanceof com.HTMLReceiver)) {
throw new com.IllegalArgumentException(
name + " is not an instance of com.HTMLReceiver.");
}
我想将此代码分解为一个通用方法,这样我就可以这样调用它:
Helper.checkInstance(receiver, "com.HTMLReceiver");
但我不知道如何转换 < code>com.HTMLReceiver 从字符串到其实际类型,以便我可以在其上使用 instanceof
。
有办法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将其称为:
这将不允许您打印类型名称(“com.HTMLReceiver”)。
或者:
您在打印中使用用户字符串。
请注意,同一类型可以有多个类型名称
foo
和com.HTMLReceiver
是同一事物的名称。JavaScript 本身无法从类型转到类型名称。
如果只传入String,我认为唯一通用的解决方案是eval。
I would call it as:
This will not allow you print a type name ("com.HTMLReceiver").
or:
You use the user string in the print.
Note that the same type can have multiple type names
foo
andcom.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.