Problem to Type casting - java

I am using Bonita Api Java docs(Bonita Api) to get the instanceUUID of process and get the instanceUUID of type ProcessInstanceUUID.using getValue(), i am convert the object value in string and send another java class where i want to typecast String into ProcessInstanceUUID class object type.
it is possible,if possible please give me some idea to solve this problem.
ProcessInstanceUUID instanceUUID = this.getProcessInstanceUUID();
instanceUUIDValue = instanceUUID.getValue();
Thanks

Why do you want to convert the object to string, and reconvert it back to ProcessInstanceUUID object?
You can pass the ProcessInstanceUUID object itself.
BTW, typecasting is not what you think. It is not a mechanism to convert from any object type any other object.

From the API:
ProcessInstanceUUID instanceUUID = this.getProcessInstanceUUID()
String instanceUUIDValue = instanceUUID.getValue();
ProcessInstanceUUID newUUID = new ProcessInstanceUUID(instanceUUIDValue);
As #Nivas said, this is not typecasting. Here is an example of type casting:
Object obj1 = "Hello World"; // obj1 is in fact a String
Object obj2 = new Integer(2); // obj2 is an Integer
String myString1 = (String) obj1; // explicitly type cast an Object to String
// The next statement will throw an exception at runtime because obj2 is not a String
String myString2 = (String) obj2;

Related

Performance of methods casting Object to String [duplicate]

What is the difference between
Object foo = "something";
String bar = String.valueOf(foo);
and
Object foo = "something";
String bar = (String) foo;
Casting to string only works when the object actually is a string:
Object reallyAString = "foo";
String str = (String) reallyAString; // works.
It won't work when the object is something else:
Object notAString = new Integer(42);
String str = (String) notAString; // will throw a ClassCastException
String.valueOf() however will try to convert whatever you pass into it to a String. It handles both primitives (42) and objects (new Integer(42), using that object's toString()):
String str;
str = String.valueOf(new Integer(42)); // str will hold "42"
str = String.valueOf("foo"); // str will hold "foo"
Object nullValue = null;
str = String.valueOf(nullValue); // str will hold "null"
Note especially the last example: passing null to String.valueOf() will return the string "null".
String.valueOf(foo) invokes foo's .toString() method and assigns the result to the the bar. It is null and type safe operation.
Casting will just assign foo to the bar, if the types are matching. Otherwise, the expression will throw a ClassCastException.
Casting means that the object needs to be of type String, while String.valueOf() can take other types as well.
Both generates same output in case of String.
Casting fails in case of provided object is Not a string.
String.valueOf method is used to get the String represenation of it's parameter object.
(String) value casts object value to string.
You can use the String.valueOf method to get the String representation of an object without worrying about null references. If you try to cast String on a null reference you would get a NullPointerException.
final Object obj = null;
final String strValOfObj = String.valueOf(obj);
final String strCastOfObj = (String) obj;
if (strValOfObj == null) System.out.println("strValOfObj is null");
if (strCastOfObj == null) System.out.println("strCastOfObj is null");
Output: strCastOfObj is null
The first one i.e, String.valueOf returns a string only if the object is a representable type which is a value type or a String.. Else it throws the exception.
In the latter one, you are directly casting which can fail if the object isn't a string.
Online example.
http://ideone.com/p7AGh5
in String.valueOf(); string as work typecasting all the argument passed in valueof() method convert in String and just like integer.string() convert integer into string only

Speaking of converting int type to String type in Java

Why sometimes cast will not work but String.valueOf() will? Aren't they all exist for same functionality of converting current type to String?
For example:
addgui.getIdField().setText(String.valueOf(jtable.getValueAt(rowNum, 0)));
here jtable.getValueAt(rowNum, 0) returns an Integer value and if I directly cast it to String it causes eroor, but String,valueOf works instead.
Remember that String.valueOf(Object) invokes Object.toString(), creates a String out of it and assigns it to the the Object.
Casting will just assign object2 to the object1, If both have same type it will work. Otherwise, the expression would throw a ClassCastException.
Example
Object a1 = "abc";
String s =(String)a1; //this works
But this shall give you a ClassCastException
int b = 1;
Object c = b;
String s1 =(String)c;
Where as String.valueOf() converts whatever to pass to it as a String

java.lang.ClassCastException at runtime

I'm getting a ClassCastException in the follow code:
Destination[] destinations;
ArrayList<Destination> destinationsList = new ArrayList<Destination>();
// .....
destinations = (Destination[]) destinationsList.toArray();
My Destination class looks like this:
public class Destination {
private String code;
Destination (String code) {
this.code = code;
}
public String getCode () {
return code;
}
}
Syntactically I'm not getting any errors, this only occurs at run time. It's confuzing though because aren't all classes essentially derivatives of the Object class? And if so, why does this cast conversion error even occur?
toArray() returns an Object[]. What you need is toArray(T[] a) because of the type erasure, a generic collection cannot create a typed array.
By using the overloaded method, you can help it to create a typed array of Destination objects.
Use
destinations = destinationsList.toArray(new Destination[destinationList.size()]);
because toArray returns an object array not your Destination[]
replace it with this
destinations[] = destinationsList.toArray(new Destination[destinationList.size()]);
this would populate the new Destination Array object and return the populated array.
Edit:
To answer your question in comment in #ZouZou's answer.
you need the new Destination[] because a Destination[] can be referred by a Object[] but the other way round is not possible.
to clarify things,
String s = "hello";
Object o = s;
s = (String) o; //works
//but
String s = "hello";
Object o = s;
o = new Object;
s = (String) o; //gives you a ClassCastException because an Object
//cannot be referred by a string
Because a String has all the properties defined in the Object class through inheritence but an Object doesn't possess the properties of a String object. That is why it is legal to cast up the inheritence tree and downcasting is not.
It is not implemented on the language level because of how generics are put in the language. Also do not try something like this :
// Destination[] destinations;
ArrayList<Destination> destinationsList = new ArrayList<Destination>();
//add some destinations
destinationsList.add(new Destination("1"));
destinationsList.add(new Destination("2"));
// .....
Object[] destinations = destinationsList.toArray();
destinations[1] = "2"; //simulate switching of one object in the converted array with object that is of other type then Destination
for (Object object : destinations) {
//we want to do something with Destionations
Destination destination = (Destination) object;
System.out.println(destination.getCode()); //exception thrown when second memeber of the array is processed
}
Use this :
destinations = destinationsList.toArray(new Destination[0]); //yes use 0

Java Cast from Object to long to String

Here's the situation, I have an Object in a Map which I explicitly know to contain an instance of Long and I need to turn that value into a string but keep getting incompatible type errors. Here's what my code looks like:
Map<String, Object> map = ...;
Object obj = new Long(31415L);
String str = Long.valueOf((long)map.get("id")); //Problem line
This gives:
Inconvertible types.
Found : java.lang.Object
Required: long
Any suggestions as to how to get around this?
You can just do
String str = map.get("id").toString();
Use, for instance:
String.valueOf(map.get("id"))
The problem is that you try and cast an object to a primitive type. That cannot work.
But since the values of your map will be Longs anyway (collections cannot contain primitive types, save for specialized implementations such as found in GNU Trove), look at #BheshGurung's answer...
You can use the toString function;
public String toString() {
return String.valueOf(map.get("id"))
}
String str = map.get("id").toString();
You have 2 issues here:
You created a *L*ong, not a *l*ong. Therefore you need to cast back to a *L*ong, not a *l*ong.
In order to get the String representation of a *L*ong you must call toString() on it.
Use this:
String str = ((Long)map.get("id")).toString();

Difference between casting to String and String.valueOf

What is the difference between
Object foo = "something";
String bar = String.valueOf(foo);
and
Object foo = "something";
String bar = (String) foo;
Casting to string only works when the object actually is a string:
Object reallyAString = "foo";
String str = (String) reallyAString; // works.
It won't work when the object is something else:
Object notAString = new Integer(42);
String str = (String) notAString; // will throw a ClassCastException
String.valueOf() however will try to convert whatever you pass into it to a String. It handles both primitives (42) and objects (new Integer(42), using that object's toString()):
String str;
str = String.valueOf(new Integer(42)); // str will hold "42"
str = String.valueOf("foo"); // str will hold "foo"
Object nullValue = null;
str = String.valueOf(nullValue); // str will hold "null"
Note especially the last example: passing null to String.valueOf() will return the string "null".
String.valueOf(foo) invokes foo's .toString() method and assigns the result to the the bar. It is null and type safe operation.
Casting will just assign foo to the bar, if the types are matching. Otherwise, the expression will throw a ClassCastException.
Casting means that the object needs to be of type String, while String.valueOf() can take other types as well.
Both generates same output in case of String.
Casting fails in case of provided object is Not a string.
String.valueOf method is used to get the String represenation of it's parameter object.
(String) value casts object value to string.
You can use the String.valueOf method to get the String representation of an object without worrying about null references. If you try to cast String on a null reference you would get a NullPointerException.
final Object obj = null;
final String strValOfObj = String.valueOf(obj);
final String strCastOfObj = (String) obj;
if (strValOfObj == null) System.out.println("strValOfObj is null");
if (strCastOfObj == null) System.out.println("strCastOfObj is null");
Output: strCastOfObj is null
The first one i.e, String.valueOf returns a string only if the object is a representable type which is a value type or a String.. Else it throws the exception.
In the latter one, you are directly casting which can fail if the object isn't a string.
Online example.
http://ideone.com/p7AGh5
in String.valueOf(); string as work typecasting all the argument passed in valueof() method convert in String and just like integer.string() convert integer into string only

Categories