Manually Parsing an Object to get a Value from a Field

So, in this use case we had an issue where entities in Java were throwing class cast exceptions for some reason or the other and it started to become a huge time barrier for us as we had no solutions or workarounds.

Many of the solutions I found online suggested deserializing the object and reserializing it and that is what we are doing here in these Utility Methods.

Getting a String from a Field:

public static String getStringFromField(Object objectName, String fieldName) {
String stringToReturn;

try {
//System.out.println(“Declaring the Class”);
Class<?> c = objectName.getClass();

//System.out.println(“Assigning the Field Name”);
Field f = c.getDeclaredField(fieldName);

//System.out.println(“Setting Field to Accessible”);
f.setAccessible(true);

try {
stringToReturn = (String) f.get(objectName).toString();
} catch (Exception exception) {
System.out.println(exception);
stringToReturn = “”;
}

return stringToReturn;
} catch (Exception exception) {
System.out.println(“Something went wrong with the getStringFromFieldMethod… Panic!”);
exception.printStackTrace();

stringToReturn = “Error, Contact System Admin!”;

return stringToReturn;
}
}

Getting an Integer from a Field:

public static Integer getIntegerFromField(Object objectName, String fieldName) {
Integer integerToReturn;

try {
Class<?> c = objectName.getClass();

Field f = c.getDeclaredField(fieldName);

f.setAccessible(true);

String integerToConvert = (String) f.get(objectName).toString();

integerToReturn = Integer.parseInt(integerToConvert);

return integerToReturn;
} catch (Exception exception) {
System.out.println(“Something went wrong with the getIntegerFromFieldMethod… Panic!”);
exception.printStackTrace();

integerToReturn = 0;

return integerToReturn;
}
}

Getting a BigDecimal from a Field:

public static BigDecimal getBigDecimalFromField(Object objectName, String fieldName) {
BigDecimal numberToReturn;

try {
Class<?> c = objectName.getClass();

Field f = c.getDeclaredField(fieldName);

f.setAccessible(true);

String numberToConvert = (String) f.get(objectName).toString();

numberToReturn = new BigDecimal(numberToConvert);

return numberToReturn;
} catch (Exception exception) {
System.out.println(“Something went wrong with the getBigDecimalFromFieldMethod… Panic!”);
exception.printStackTrace();

numberToReturn = new BigDecimal(0);

return numberToReturn;
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s