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.
net. URL. java.lang.Object | +--java.net.URL public final class URL extends Object implements Serializable, Comparable Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web.
Constructors of the URL classURL(URL context, String spec): Creates a URL object by parsing the given spec in the given context. URL(String protocol, String host, int port, String file, URLStreamHandler handler): Creates a URL object from the specified protocol, host, port number, file, and handler.
URL stands for Uniform Resource Locator and represents a resource on the World Wide Web, such as a Web page or FTP directory. This section shows you how to write Java programs that communicate with a URL.
URLConnection Class in Java. The URLConnection class in Java helps to represent a “connection or communication” between the application and the URL. This class also helps us to read and write data to the specified resource of URL.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With