I would say that an alternative strategy, if you want to work with primitives, is to do what the Java libraries do. Just suck it and use several methods.
For example, ObjectInputStream has readDouble() , readByte() , etc.
You do not type anything by sharing the implementation of the function, and the clients of your function do not receive anything according to the variants of your function that have the same name.
UPDATE
Given your update, I don't find it necessary to duplicate too much code. It depends on your coding strategy, but I would suggest that you could do something like this:
private byte get8Bits(); public byte getByte() { return get8Bits(); } public int getInt() { return (get8Bits() << 24) | (get8Bits() << 16) | (get8Bits() << 8) | get8Bits(); }
Anything that divides the code more than this is probably too complicated.
An alternative could be
private long getBits(int numBits); public byte getByte() { return (byte)getBits(8); } public int getInt() { return (int)getBits(32); }
i.e. I don’t think it makes sense to expose your library users to anything other than the primitive types themselves.
If you really wanted to, then you could do one way to access as follows:
@SuppressWarnings("unchecked") public static <T> T getValue(Class<T> clazz) { if ( clazz == byte.class ) { return (T)Byte.valueOf((byte)getBits(8)); } else if ( clazz == int.class ) { return (T)Integer.valueOf((int)getBits(32)); } throw new UnsupportedOperationException(clazz.toString()); }
But I do not see how this is less cumbersome for the clients of your library.
Mark peters
source share