Supuhstar Supuhstar - 6 months ago 9
Java Question

How can I create a static final java.net.URL?

My question is simple. I'm trying to make a set of

java.net.URL
s that are
public static final
, so that any class can access them from any context, as these URLs won't change during runtime. However, when I try to create them, I get a compiler error telling me that I must catch or declare thrown a
java.net.MalformedURLException
, but that is impossible outside a method. Is there any way to circumvent such a constructor that throws a non-
java.lang
Throwable?


Some dummy code below to visualize my problem:

public class Main
{
public static final java.net.URL STATIC_URL = new java.net.URL("http://example.com/");
public static void main(String[] args)
{
GUI gui = new GUI();
gui.setVisible(true);
}
}




public class GUI extends java.awt.Window
{
public GUI()
{
add(new java.awt.Label(Main.STATIC_URL.toString()));
}
}


If you try to compile this, it will tell you that you can't because of line 3. Hence my question.

Answer

Use a static initializer:

public class Main {
    private static final java.net.URL STATIC_URL;
    static {
        java.net.URL temp;
        try {
            temp = new java.net.URL("http://www.example.com");
        } catch (java.net.MalformedURLException e) {
            temp = null;
        }
        STATIC_URL = temp;
    }
}

Note: The usage of a temporary variable is required to avoid a compilation error about assigning to the final static field twice. If the field is not final, the assignment could be done directly.