Monday, September 17, 2007

Determine Local IP Addresses

Here's a quick how-to for determining the IP Addresses your local machine has.

NOTE: This version (i've edited the post a couple of times now), will return all IPs associated with any network interface on the machine. Also, it's been tested on Windows and several flavors of linux.



public ArrayList getIPs() throws SocketException {
ArrayList ips = new ArrayList();
Enumeration m = NetworkInterface.getNetworkInterfaces();
while(m.hasMoreElements()) {
NetworkInterface ni = m.nextElement();
Enumeration addresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
String ip = address.getHostAddress();

// filter out Inet6 Addr Entries
if (ip.indexOf(":") == -1) {
ips.add(ip);
}
}
}

return ips;
}

Thursday, September 13, 2007

Generic toString()

Do you ever want a descriptive toString() of a class you just created, but don't feel like taking the time to write it? Here's a generic toString() that uses the java.lang.reflect package and will work in any class.

Note:
This isn't the end-all generic toString() method. It does the bare minimum of printing out each field and its value with the added ability to handle null values and arrays.



@Override
public String toString() {
Field[] fields = getClass().getDeclaredFields();
AccessibleObject.setAccessible(fields,true);

StringBuffer sb = new StringBuffer();
sb.append("Class: " + this.getClass().getName() + "\n");

for (Field field : fields) {
Object value = null;
try {
value = field.get(this);
} catch (IllegalAccessException e) {continue;}

sb.append("\tField \"" + field.getName() + "\"\n");

Class fieldType = field.getType();
sb.append("\t\tType: ");

if (fieldType.isArray()) {
Class subType = fieldType.getComponentType();
int length = Array.getLength(value);
sb.append(subType.getName() + "[" + length + "]" + "\n");

for (int i = 0; i < length; i ++) {
Object obj = Array.get(value,i);
sb.append("\t\tValue " + i + ": " + obj + "\n");
}
} else {
sb.append(fieldType.getName() + "\n");
sb.append("\t\tValue: ");
sb.append((value == null) ? "NULL" : value.toString());
sb.append("\n");
}
}
return sb.toString();
}



Example Output

Class: GenericToString
- Field "myint"
Type: int
Value: 9
- Field "myDouble"
Type: java.lang.Double
Value: 999.095
- Field "myString"
Type: java.lang.String
Value: My String
- Field "myNullObject"
Type: java.lang.Object
Value: NULL
- Field "myStringArray"
Type: java.lang.String[2]
Value 0: one
Value 1: two
- Field "myintArray"
Type: int[3]
Value 0: 1
Value 1: 2
Value 2: 3
- Field "myHashMap"
Type: java.util.HashMap
Value: {val3=3, val1=val1, val2=val2}