I am consuming lot of elements(Fields) from webservice response. Most of the elements datatypes are BigDecimal
, BigInteger
, xmlGregorianCalender
, String
, int
etc not collections.
My requirement is i need to write a utility method that should return a string value irrespective of type.
I googled everywhere but i was unable to find the solution. Please guide me to achieve this.
I tried the following based on reply's.But i am not getting the proper output
BigDecimal big = new BigDecimal(10);
BigInteger bigInt = new BigInteger("12334");
String sampleStr1 = ToStringBuilder.reflectionToString(big);
String sampleStr2 = ToStringBuilder.reflectionToString(bigInt);
System.out.println("big::"+sampleStr1+"::bigint::"+sampleStr2);
Output :
big::java.math.BigDecimal@2afa3ac1[intVal= <null>,scale=0]::bigint::java.math.BigInteger@72291aff[signum=1,mag={12334},bitCount=0,bitLength=0,lowestSetBit=0,firstNonzeroIntNum=0]
Expected output :
big::10::bigint::12334
Would the toString()
method suffice. It should be implemented on all classes and should produce the best summary of the object in question.
Otherwise, you could create your own wrappers of these objects and convert the to JSON or XML using Jackson or JAXB
Try using ToStringBuilder .reflectionToString() available in apache commons library.
Sample Code:
public class Test {
BigDecimal big = new BigDecimal(10);
BigInteger bigInt = new BigInteger("12334");
public String toString() {
**ToStringBuilder.setDefaultStyle(ToStringStyle.SIMPLE_STYLE);**
return ToStringBuilder.reflectionToString(this);
}
public static void main(String args[]) {
Test test = new Test();
System.out.println(test);
}
}
Returns response in the format:
Class@ObjectAddress[field=value,..]
Test@1f4e8ac9[big=10,bigInt=12334]
Setting the above style would give just the values as
10,12334
I have overridden toString() to get finer control. I am not sure how to correct the output with direct access to Integer/BigDecimal.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.