简体   繁体   中英

How to tell if my program is running as an Applet, or as an Java Application

I've written a clunky little breakout clone & I'm writing to disk for save games and high scores.

Is there an easy way for me to check if my program is running as an applet, or as an application?

eg...

if(!anApplet){
//Include disk i/o features
}

I've tried setting a boolean variable in the 'main' class, setting it to false with init(), and true in the main method but no luck so far. Will keep trying regardless, but thanks in advance for any advice!

Use the AccessController . You could wrap all calls in an AccessController.doPrivileged block.

AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            // privileged code goes here, for example, read and writing files.
            ...
            return null; // nothing to return
        }
});

You could also, if necessary, establish the permissions that you application has, on startup, and use them later:

Boolean flag = AccessController.doPrivileged(new PrivilegedAction() {
        public Boolean run() {
            boolean flag = false;
            // privileged code goes here, for example, read and writing files. If it succeeds, set flag to true.
            ...
            return flag; // return true, if the privileged action succeeded
        }
});

I would recommend using the first approach. If you do use the second, then make the flag variable final in nature; you'll therefore need to perform any "privilege testing" in the constructor of the class that stores this flag.

Addendum

The snippets of code will continue to throw AccessControlException s, if they are encountered. If you want to continue processing, without hindering the user, then you'll have to catch them, while setting the flag to false. The AccessController.doPrivilege block exists to check if the permission exists for the current stack frame.

Addendum #2

Using AccessController.checkPermission is not recommended, unless you can guarantee the presence of a Security Manager, and an appropriate policy file. In the absence of a Security Manager, this method will always throw an exception for a permission check, which would be undesirable when the application is not running as an applet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM