I’m using this code to set the macOS dock icon of my JavaFX app:
try { // Sets macOS dock icon: com.apple.eawt.Application.getApplication().setDockIconImage(SwingFXUtils.fromFXImage(appIcon, null)); } catch (Exception e) { // Doesn’t work on Windows and Linux }
I can’t run the app on Windows because it throws the error “java: package com.apple.eawt does not exist”
How can I catch a “package x does not exist” error or check if it exists at runtime?
Advertisement
Answer
You can’t – it’s a compiler error, you can’t catch those at runtime. But the notion of ‘can I run this code if the class is there, but not run it otherwise’ – yeah you can do that, you just have to use reflection, which basically turns compile time stuff into runtime stuff:
public boolean trySetMacOsDockIcon(Image img) { try { Class<?> c = Class.forName("com.apple.eawt.Application"); Method m = c.getMethod("getApplication"); Object application = m.invoke(null); m = application.getClass().getMethod("setDockIconImage", Image.class); m.invoke(application, img); return true; } catch (Exception e) { return false; } }
you may want to log those exceptions, at least until you tested this once or twice.
m.invoke(null)
invokes the method; the first argument is the ‘receiver’ (the thing to the left of the dot); for static methods, there is no receiver and the parameter doesn’t do anything. getApplication
is static, so we pass null there. The second invoke
line is an instance method on apple’s Application class, so there we do need to pass in a value, namely, the application object we got by invoking getApplication
. The second parameter there is simply the params for that method, so, we pass the image.