Is it possible to define custom autoboxing in Java?
I need to automatically convert java.lang.Number
into my class org.expr.NumberExpression
when typing parameters of a function. For two parameters, I ended up writing four very similar methods:
public class Assemble {
public NumberExpression add(NumberExpression a, NumberExpression b) {
// do something
}
public NumberExpression add(NumberExpression a, Number b) {
return add(a, new NumberConstant(b));
}
public NumberExpression add(Number a, Number b) {
return add(new NumberConstant(a), new NumberConstant(b));
}
public NumberExpression add(Number a, NumberExpression b) {
return add(new NumberConstant(a), b);
}
}
So I can type:
assemble.add(5, assemble.add(7, 3));
assemble.add(5, assemble.add(7, 3), 8, 15); // does not work
However, I think this becomes unmanageable for 10 parameters (that I wanted to do); I guess I would need to write 1024 similar methods.
The other solution I was thinking about is to write a method like:
public NumberExpression add(NumberExpression... numbers) {
// do something
}
But would I be able to type Number
and NumberExpression
mixed together as parameters?