Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there .Net TypeConverter equivalent in Java

In .NET when I had a "value" that could exist as multiple types I could easily use a TypeConverter for switching between those types (currency types, xml data vs object representation, ect). In Java, I am not sure what the preferred way to handle this situation is. Is there a TypeConverter equivalent in Java?

like image 379
insipid Avatar asked Feb 16 '10 21:02

insipid


1 Answers

For someone from a .NET world it is going to be a surprise that there isn't one out of the box. This is because we have things like primitives (int, long) etc, their primitive-wrappers (Integer, Long etc), autoboxing from int to Integer when you require (this is from JDK 1.5).

So we the poor Java developers manually convert things (some examples given above by @Boolean) Also the endless hassles of using == operators when doing these. For ex: Autoboxed integers of upto 127 are cached.

public void testsimple() {
    Integer a = 124, b = 124, c = 500, d= 500;
    System.out.println(a == b); //prints true in JDK 1.6
    System.out.println(c == d); //prints false in JDK 1.6
}

If you are writing a huge app that needs too much data conversion you can write something on your own. Spring's "TypeConverter" interface can be a decent start.

Use this link http://imagejdocu.tudor.lu/doku.php?id=howto:java:how_to_convert_data_type_x_into_type_y_in_java if you have some trouble

like image 192
Kannan Ekanath Avatar answered Oct 23 '22 12:10

Kannan Ekanath