java 返回泛型_Java泛型返回类型

现在我有两个相同的方法,比如:

default Byte readByte(InputStream stream) {

ByteBuffer bytes = ByteBuffer.allocate(Byte.BYTES);

bytes.order(ByteOrder.nativeOrder());

while (0 != bytes.remaining()) {

try {

bytes.put((byte)stream.read());

}

catch (Exception e) {

e.getStackTrace();

}

}

bytes.rewind();

return bytes.get();

}

...

default Short readShort(InputStream stream) {

ByteBuffer bytes = ByteBuffer.allocate(Short.BYTES);

bytes.order(ByteOrder.nativeOrder());

while (0 != bytes.remaining()) {

try {

bytes.put((byte)stream.read());

}

catch (Exception e) {

e.getStackTrace();

}

}

bytes.rewind();

return bytes.getShort();

}

同样的整数,浮点,双精度,还有比我想的更通用的方法?

我的尝试,例如:

private T read(InputStream stream) {

ByteBuffer bytes = ByteBuffer.allocate(T.BYTES);

bytes.order(ByteOrder.nativeOrder());

while (0 != bytes.remaining()) {

bytes.put((byte)stream.read());

}

bytes.rewind();

switch (T.class) {

case Byte.TYPE: return bytes.get();

case Short.TYPE: return bytes.getShort();

case Integer.TYPE: return bytes.getInt();

case Long.TYPE: return bytes.getLong();

case Float.TYPE: return bytes.getFloat();

case Double.TYPE: return bytes.getDouble();

default:

throw new UnsupportedTypeException(T.class);

}

}

所以,但它并不像我想的那样有效,Java!= C++ + ok。那么有没有什么方法可以用普通的风格来做呢?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值