简体   繁体   English

我怎样才能创建一个静态的最终java.net.URL?

[英]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. 我正在尝试创建一组public static finaljava.net.URL ,以便任何类都可以从任何上下文访问它们,因为这些URL在运行时不会更改。 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. 但是,当我尝试创建它们时,我收到编译器错误,告诉我必须捕获或声明抛出java.net.MalformedURLException ,但这在方法之外是不可能的。 Is there any way to circumvent such a constructor that throws a non- java.lang Throwable? 有没有办法绕过这样一个抛出非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. 如果你试图编译它,它会告诉你,你不能因为第3行。因此我的问题。

An "alternative" which I'd prefer to @HosamAly method: 一个“替代”,我更喜欢@HosamAly方法:

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. 如果该字段不是final字段,则可以直接完成分配。

If you're sure you want to hardwire a URL. 如果您确定要硬连线URL。 Are you sure? 你确定吗? java.net.URL is one of the most comprehensively broken classes in the JDK. java.net.URL是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). 关于用作“常量”,涉及DNS查找,它使用可变静态(虽然安全检查保护,如果安装了SecurityManager )。

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. 注意: 你真的不想要null - 抛出某种错误并停止加载类。 I've made the constant private as it really isn't the sort of thing you want dependencies on. 我已经使常量private因为它实际上并不是你想要依赖的东西。

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. 我编译它的唯一方法是删除final并使用静态初始化程序块。

/**
 * 
 */
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

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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