I would like to call a method which could potentially take on different versions, i.e. the same method for input parameters that are of type:
- boolean
- byte
- short
- int
- long
The way I would like to do this is by "overloading" the method (I think that is the correct term?):
public void getValue(byte theByte) {...}
public void getValue(short theShort) {...}
... etc ...
... but that would mean that I would have to pass the primitive type in by reference... similar to C++ where the method has external effect, where it can modify the variable outside its scope.
Is there a way to do this without creating new classes or using the Object versions of the primitive types? If not, any suggestions on alternative strategies?
Let me know if I should further explain to clear up any confusion.
UPDATE
What I'm actually trying to do is construct the primitive type from a set of bits. So if I'm dealing with the byte version of the method, I want to pretty much do my work to get 8 bits and return the byte (since I can't pass by reference).
The reason I'm asking this question is because the work I do with bits is very repetitive and I don't want to have the same code in different methods. So I want to find a way for my ONE method to KNOW how many bits I'm talking about... if I'm working with a byte, then 8 bits, if I'm working with a short, 16 bits, etc...
I would say the alternative strategy, if you want to work with primitives, is to do what the Java Libraries do. Just suck it up and have multiple methods.
For example, ObjectInputStream has
readDouble()
,readByte()
, etc.You're not gaining anything by sharing an implementation of the function, and the clients of your function aren't gaining anything by the variants of your function all having the same name.
UPDATE
Considering your update, I don't think it's necessary to duplicate too much code. It depends on your encoding strategy but I would imagine you could do something like this:
Anything that shares code more than that is probably over-engineering.
An alternative could be
i.e. I don't think it makes sense to expose the users of your library to anything other than the primitive types themselves.
If you really, really wanted to then you could make a single method for access like this:
But I fail to see how it's any less cumbersome for clients of your library.
Primitives are not passed by references (or objects for that matter) so no you cannot.
Prints out 1
Only by creating your own value holding types.