简体   繁体   中英

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.

An "alternative" which I'd prefer to @HosamAly method:

private static final java.net.URL STATIC_URL = makeUrl("http://www.example.com");

public static java.net.URL makeUrl(String urlString) {
    try {
        return new java.net.URL(urlString);
    } catch (java.net.MalformedURLException e) {
        return null; //Or rethrow an unchecked exception
    }
}

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.

If you're sure you want to hardwire a URL. Are you sure? java.net.URL is one of the most comprehensively broken classes in the JDK. In regards to use as a "constant", there is DNS lookup involved and it uses a mutable static (albeit one guarded by a security check, if you have a SecurityManager installed).

If it's just one, a static initialiser should be fine.

private static final java.net.URL STATIC_URL;

static {
    try {
        STATIC_URL = new java.net.URL("http://example.com/");
    } catch (java.net.MalformedException exc) {
        throw new Error(exc);
    }
}

(Note, you can't qualify the static field name with the class name.)

Note: You really do not want a null - throw an error of some sort and stop the class loading. I've made the constant private as it really isn't the sort of thing you want dependencies on.

If you have lots, then a method for the common code and assignment at the site of the definition is appropriate.

private static final java.net.URL STATIC_URL = constantURL("http://example.com/");

private static URL constantURL(String str) {
    try {
        return new java.net.URL("http://example.com/");
    } catch (java.net.MalformedException exc) {
        throw new Error(exc);
    }
}

Again, no nulls!

The only way I got this to compile is by removing final and using the static initializer block.

/**
 * 
 */
package com.neurologic.example;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author The Elite Gentleman
 * @since 06 December 2011
 *
 */
public class StaticUrlTest {

    public static URL url = null;

    static {
        try {
            url = new URL("http://www.google.com");
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}

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