Reputation: 1232
I'm writing a Java program that implements some program analysis. As part of this, I want a type for representing "values" in the programs that I'm analysing. Values, for my purposes, are just integers. However, I would rather not use the int
/Integer
types in my code, because int
/Integer
are not a very descriptive names. I would rather write Value
. I would then like to write
class Value extends Integer {}
and be done. But this doesn't work because Integer
is a final class. So my current solution is to give my Value
class an int
field and then manually implemented all the various standard methods:
class Value {
int val;
public String toString() {...}
public int hashCode() {...}
public boolean equals(...) {...}
...
}
This feels like overkill when I'm really just looking for class that behaves like Integer
but has a more descriptive name.
What are my options here?
Upvotes: 0
Views: 376
Reputation: 65811
You can wrap almost anything in a proxy:
class Value<T extends Number> extends Number {
final T v;
public Value(T v) {
this.v = v;
}
@Override
public int intValue() {
return v.intValue();
}
@Override
public long longValue() {
return v.longValue();
}
@Override
public float floatValue() {
return v.floatValue();
}
@Override
public double doubleValue() {
return v.doubleValue();
}
@Override
public String toString() {
return v.toString();
}
@Override
public int hashCode() {
return v.hashCode();
}
@Override
public boolean equals(Object obj) {
return v.equals(obj);
}
}
Upvotes: 1