检测小程序上下文(我在小程序内吗?)
我想知道 Java 类是否有办法确定它是否在小程序中使用?
也就是说,我有一个可供第 3 方应用程序和小程序使用的库(一个 .jar 文件)。它确实可以在小程序中工作,但我想做一些不同的事情,具体取决于该库是否在小程序中使用 - 例如显示小程序适用的错误,避免本地文件 I/O 等。
这会很好比如说,如果 Applet.getAppletContext() 是静态的,那么即使我没有 applet 实例,我也可以调用它(并获取 NULL 或非 NULL),但可惜,它不是。还有其他办法吗?
I'm wondering if there's a way for a Java class to figure out if it is being used within an applet?
That is, I have a library (a .jar file) that can be used by 3rd-party applications and applets. It does work within applets, but I'd like to do some things differently, depending on whether or not the library is used in an applet - like show applet-applicable errors, avoid local file I/O, etc.
It would be nice if, say, Applet.getAppletContext() was static so that I could call it (and get NULL or not NULL) even if I don't have an applet instance, but alas, it isn't. Is there any other way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
检测它是否作为小程序运行的另一种方法是在发生安全异常时使用后备方法。当在另一个环境中使用时,例如具有安全上下文的 servlet 容器,这将是有利的。
例子:
An alternative to detecting whether it's running as an applet or not is to use fallback methods if a security exception occurs. This will be advantageous when used in another environment eg a servlet container with a security context.
Example:
根据 Java 安全概述白皮书(第 14 页第 2 段) )
这应该意味着对 System.getSecurityManager() 的调用将在小程序中返回非 null,而不在小程序中时将返回 null。例外情况也是可能的,例如,可以在运行程序时从命令行指定安全管理器。
According to the Java Security Overview Whitepaper (Page 14 paragraph 2)
That should mean that a call to System.getSecurityManager() will return non-null in an applet and will return null when not in an applet. Exceptions are possible, for example a security manager can be specified from the command line when running the program.
也许最安全的方法是让用户告诉您它是否在小程序中(只需将“布尔”变量添加到适当的构造函数和/或方法中。
当然,您需要更自动的东西来避免这种情况,但是,据我所知,没有确定的方法可以知道程序如何跨虚拟机运行,我可能会首先查看像 torak 在他/她的答案中建议的安全管理器,而不是。只是寻找 null 我会检查它是什么类型,但没有发现小程序使用的安全管理器类是否有任何类型的“标准”名称
。让图书馆的用户做出决定,因为他们将拥有所需的信息。
Probably the safest way is to have the user tell you if it is in an applet (just add a "boolean" variable to the appropriate constructor(s) and/or method(s).
Of course you want something more automatic to avoid that, but, as far as I know, there is no sure fire way of knowing how a program is being run that works across VMs. I would probably start by looking at the security manager like torak suggested in his/her answer, but rather than just look for null I'd check what type it is. I looked around a bit but did not find out if there is any sort of "standard" name for the security manager class that applets use.
In the end, the safest way will be to get the user of your library to decide, as they will have the information that is needed.