Question

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?

Was it helpful?

Solution

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

OTHER TIPS

Well you can typecast things... for example if you have a List object that contained strings.. you would grab a String from the list like this:

List aList = new List();
aList.add("Hello World);
String s = (String) aList.get(0);

If you are trying to convert a string to a number.. you would do something similar to this:

String aString = "200";
int i = Integer.Parse(aString);

I cheat when converting an integer to a string by doing this:

int i = 200;
String s = "" + i;

TypeConverter where added to .net partly to allow interactive UI designers to show values as string and let the user edit propriety values of types the UI designer does not understand.

I think TypeConverter is also used by data binding.

The fact you can use TypeConverter in your own software to convert between types you know at compile time is a side effect and not the primary use case they were created for.

As Java has never tried to support “RAD” tools, it has not had the same need for TypeConverter and PropertyDescriptors etc. To some extent .net was designed to allow the same sort of UI development that VB6 enabled.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top