I have a Value Class and there is an Object value in it. I want to use the value as String, Integer or Double.
The asDouble method controls instanceof value object. If it is not Double or Integer returns 0.
Generally it works but sometimes although it is Double returns 0;. I couldn't the reason of it.
When I debug I can see:

Here is my Value class
public class Value{
public Object value;
public Value(Object value) {
this.value = value;
}
public Double asDouble() {
if (this.value instanceof Integer || this.value instanceof Double) {
return Double.parseDouble(String.valueOf(this.value));
} else {
return 0.0;
}
}
}
Could anybody explain where did I go wrong
Short Answer: Details matter.
Some info: The value class instance variable (also-known-as property or member variable) is a class named Value.
Since the class Value is neither the Integer nor the Double class,
the else branch will always execute.
The Value class also has a member variable named value,
which,
in your example,
has a type of Double.
In the screen shot you included,
the Value object has its value member variable set to a "thing" which also has the type Value.
I know this because the dialog shows "value= Value (id:82)".
first at all, i agree with Ole V.V.s, killjoys and david as comments.
your screenshot shows a Value-Object holding another Value-Object in its value-property
the comments and a possible solution are summed up in the following example-class
public class Value {
// visibility should be private
private final Object value;
// to be more type-save
// and to restrict
// this.values instance-type to Double, Integer and/or String
// provide three public constructors
public Value(final Double value) {
this.value = value;
}
public Value(final Integer value) {
this.value = value;
}
public Value(final String value) {
this.value = value;
}
public double asDoublePrimitive() {
if ((this.value instanceof Number)) {
return ((Number) this.value).doubleValue();
}
return 0.0;
}
public Double asDoubleObject() {
if ((this.value instanceof Number)) {
return Double.valueOf(((Number) this.value).doubleValue());
}
return Double.valueOf(0.0);
}
}
be aware that neither your nor my code consider the case that this.value is an instanceof String
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