In java is it possible to cast a object without having to assign it to another object. For example:
Object x = Class.forName(name).newInstance();
if(x instanceof Date){
(Date)x;
x.setTime(0);
}
The compiler doesn't let me do that unless I assign it to another Date object, but is there a way in which I can cast without having to assign to another object?
Because when you assign for example: Date a = (Date)x, a and x end up being references, both being able to touch the Date methods. But to make my code cleaner, is there a way where I can cast without having to assign it?
It is valid to do this:
Object x = Class.forName(name).newInstance();
if(x instanceof Date){
((Date)x).setTime(0);
}
A cast does not change an Object, or the type of a variable. It only tells the compiler to treat the expression immediately to the right as the casted type. This only makes sense when you actually do something with the expression.
In your code you tell the compiler to treat the expression x as as Date - mind you, just the expression, not the variable.
The compiler could just ignore the cast, since it it not used any further. Apparently it was decided to flag this as an error, since in most cases it indicates a problem with the code.
See Jason's answer on how to do it correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With