Java coding notes II

  • Print all properties of an Object with name/value

public void printObjectFields(Object object) {
Field[] fields = object.getClass().getDeclaredFields();
StringBuilder msg = new StringBuilder();
String newLine = System.getProperty("line.separator");

msg.append( object.getClass().getName() );
msg.append(newLine);
Method method = null;
String methodName = "";
String methodValue = "";
for ( Field field : fields ) {
msg.append(" ");
try {
methodName = field.getName();
msg.append( methodName );
msg.append(": ");
//requires access to private field:
//field.setAccessible(true);

//run the `get` method to obtain the value
methodName = "get" + Character.toUpperCase(methodName.charAt(0)) + methodName.substring(1);
method = object.getClass().getMethod(methodName);
methodValue = String.valueOf(method.invoke(object));
msg.append(methodValue);
} catch (SecurityException e) {
} catch (NoSuchMethodException e) {
} catch ( IllegalAccessException e ) {
} catch (IllegalArgumentException e) {
} catch (InvocationTargetException e) {
}
msg.append(newLine);
}
//print msg
}
  • Compare two objects

Compare every filed of two objects by using CompareToBuilder

private int compareBrand(Brand oldBrand, Brand newBrand) {
return new CompareToBuilder().append(oldBrand.getBrandId(), newBrand.getBrandId())
.append(oldBrand.getBrandName(), newBrand.getBrandName())
.toComparison();
}
  • URL encoding of query string parameter

Either using java.net.URLEncoder:

String str = "a=b+c";
str = URLEncoder.encode(str, "UTF-8");

OR using Regex:

String str = "a=b+c";
str = str.replaceAll("\\+", "%2B").replaceAll("\\=", "%3D");

Useful link: What every web developer must know about URL encoding

  • Base64 data encoding | decoding

import java.util.Base64;
String str = "abcde"
byte[] bytes = str.getBytes("UTF-8");
String encoded = Base64.getEncoder().encodeToString(bytes);
byte[] decoded = Base64.getDecoder().decode(encoded);
strDecoded - new String(decoded);
  • Scrambling a string (scrambled email)

Recently, I need a method to generate a fake email address with existing user email…

1. Scramble a input string by shuffling all charaters with equal probablities
2. Scrambling by appending some random letters and numbers
3. First character should be a letter

Here is the code:

public static String scrambleString(Random random, String str)
{
//convert string to a char array
char charArray[] = str.toCharArray();
//random alpha and num
String randAlphaNum = RandomStringUtils.randomAlphanumeric(str.length()).toLowerCase();
//random first letter
final String allowedChars = "abcdefghijklmnopqrstuvwxyz";
char firstChar = allowedChars.charAt(random.nextInt(allowedChars.length()-1));
// Scramble the letters with equal probabilities
for( int i = 0; i < charArray.length - 1; i++ )
{
// Choose a random num from remaining numbers
int j = random.nextInt(charArray.length - 1 - i) + i;
// Swap letters
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
}
return firstChar + new String(charArray) + randAlphaNum;
}
  • A simple way to swap values

int swap(int a, int b) {    
return a;
}

//when usage
b = swap(a, a=b);

This method is a bit tricky. It relies on the fact that a will pass into swap() before b is assigned to a. Then, b is returned and assigned to a.

This method can be generic and swap any number of objects of the same type:

int swap(int a, int b, int c) {    
return a;
}

//usage
c = swap(a, a=b, b=c)
  • Convert String[] to List<String>

In order to use some util method like add(), remove(), contains()…

List<String> newCurrencies = new ArrayList(Arrays.asList(currencies));
List<String> oldCurrencies = new ArrayList();

Note: If initializing it in the following way, the size of newCurrencies will be fixed, so it cannot use some of the util methods.
E.g. List<String> newCurrencies = Arrays.asList(currencies);

  • Null-safe comparator

It’s case-insensitive with assumption of emptyString == null.

public static int nullSafeStringComparator(final Object str1, final Object str2) {
if (str1 == null ^ str2 == null) {
//particularly, we consider null == emptyString
if (String.valueOf(str1).trim().isEmpty() || String.valueOf(str2).trim().isEmpty())
return 0;
return (str1 == null) ? -1 : 1;
}
if (str1 == null && str2 == null)
return 0;
//since neither one is NULL here, toString() works
return str1.toString().compareToIgnoreCase(str2.toString());
}