Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "localhost" a constant in Java? [closed]

Tags:

java

Is "localhost" a constant anywhere in Java SE 6? It's not terribly difficult to type out, but it might be nice to have a constant in many places rather than the String. Are there standard practices around this?

Edit: I know how to create a constant. In the past, I've found constants such as org.apache.http.HttpHeaders cleaner than using my own, as they are less prone to typos or accidental edits.

like image 310
mbarrows Avatar asked Apr 20 '26 10:04

mbarrows


1 Answers

Well, you can get the local host's name like this:

InetAddress.getLocalHost().getHostName()

The previous snippet will return the local host's configured name (not really the string "localhost"). I believe you're better off writing your own constant:

public static final String LOCAL_HOST = "localhost";

And (although some people will say it's a bad practice, but that's open to debate) you can import the constant statically in any class where you need it, just replace "package.to" with the real package where the class resides and TheClass with the actual name of the class defining the constant:

import static package.to.TheClass.LOCAL_HOST;

In this way, using the constant will be a simple matter of writing LOCAL_HOST where needed.

like image 50
Óscar López Avatar answered Apr 23 '26 00:04

Óscar López