Re: Class Loading on Different Opperating Systems
- From: Chris Smith <cdsmith@xxxxxxx>
- Date: Fri, 31 Mar 2006 10:03:16 -0700
Rationem <rationem@xxxxxxxxx> wrote:
In an attempt to handle the special CMD+Q on a Mac that resides in the
application menu I had to put in the following code:
if (System.getProperty("os.name").toLowerCase().indexOf("mac")
!= -1)
{
com.apple.eawt.Application app = new
com.apple.eawt.Application();
app.addApplicationListener(new
com.apple.eawt.ApplicationAdapter() {
public void handleQuit(com.apple.eawt.ApplicationEvent
e)
{
attemptToQuit();
}
});
}
This works properly on a Mac but does not work on a windows machine
because the com.apple.eawt.* classes are not avabilible. Is there any
way I can use this code and still maintain the cross-platform aspect of
java?
Sure; reflection can do what you want. The naive way would look like
this (omitting exception handling).
if (System.getProperty("os.name").toLowerCase()
.indexOf("mac") != -1)
{
Class appc = Class.forName("com.apple.eawt.Application");
Object app = appc.newInstance();
Class lc = Class.forName(
"com.apple.eawt.ApplicationListener");
Object listener = Proxy.newProxyInstance(
getClassLoader(), new Class[] { lc },
new InvocationHandler() {
public Object invoke(
Object proxy,
Method method,
Object[] args)
{
if (method.getName().equals("handleQuit")
{
attemptToQuit();
}
}
});
Method m = appc.getMethod("addApplicationListener", lc);
m.invoke(app, listener);
}
Of course, that's the naive way. A better way would be to put all that
code into a class that implements some interface, and then do something
like this:
if (System.getProperty("os.name").toLowerCase()
.indexOf("mac") != -1)
{
AppCloseHandler h = Class.forName(
"mypackage.MacintoshCloseHandler").newInstance();
h.setupClose();
}
AppCloseHandler is an interface that you write. Inside of the class
mypackage.MacintoshCloseHandler, you can make static use of the Mac-
specific classes, since this code will only get loaded when those
classes are available.
I still find it hard to believe that WindowListener.windowClosing
doesn't work properly on the Mac... but if you've tried it, I guess I
can't argue since I don't have a Mac to try it with.
--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
.
- Follow-Ups:
- Re: Class Loading on Different Opperating Systems
- From: Steve W. Jackson
- Re: Class Loading on Different Opperating Systems
- References:
- Class Loading on Different Opperating Systems
- From: Rationem
- Class Loading on Different Opperating Systems
- Prev by Date: listen to an existing browser
- Next by Date: Re: Reflecting generics
- Previous by thread: Class Loading on Different Opperating Systems
- Next by thread: Re: Class Loading on Different Opperating Systems
- Index(es):
Relevant Pages
|