从布尔值转换为Java字节 [英] convert from boolean to byte in java

查看:133
本文介绍了从布尔值转换为Java字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要设置字节值作为方法的参数。我有布尔变量 isGenerated ,来确定要在此方法中执行的逻辑。不过,我可以直接传递布尔值,字节参数,这是不允许的,不能在java中施放。因此,解决办法我现在看起来是这样的:

I need to set byte value as method parameter. I have boolean variable isGenerated, that determines the logic to be executed within this method. But I can pass directly boolean as byte parameter this is not allowed and can't be cast in java. So the solution I have now looks like this:

myObj.setIsVisible(isGenerated ? (byte)1 : (byte)0);

但对我来说似乎很奇怪。也许一些更好的解决方案存在这样做呢?

But it seems odd for me. Maybe some better solution exists to do this?

推荐答案

您的解决方案是正确的。

your solution is correct.

如果你喜欢,你可以通过做下列方式避免一个铸造:

if you like you may avoid one cast by doing it the following way:

myObj.setIsVisible((byte) (isGenerated ? 1 : 0 ));

此外,你应该考虑以下更改您的实现之一:

additionally you should consider one of the following changes to your implementation:


  • 你的方法更改为类似的 setVisiblityState(字节状态),如果你需要考虑2个以上可能的状态

改变你的方法的 setIsVisible(布尔值)的,如果你的方法做什么它看起来像

change your method to setIsVisible(boolean value) if you're method does what it's looking like

这篇关于从布尔值转换为Java字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆