[英]Setting byte field in an object
I have a simple program as below: 我有一个简单的程序如下:
class SerializationBox implements Serializable
{
private byte serializableProp = 10;
public byte getSerializableProp()
{
return serializableProp;
}
public void setSerializableProp(byte serializableProp)
{
serializableProp = serializableProp;
}
}
public class SerializationSample
{
/**
* @param args
*/
public static void main(String args[])
{
SerializationBox serialB = new SerializationBox();
serialB.setSerializableProp(1); // Here i get an error
}
}
At the indicated place in code I get error that "The method setSerializableProp(byte) in the type SerializationBox is not applicable for the arguments (int)". 在代码中指示的位置,我得到错误“SerializationBox类型中的方法setSerializableProp(byte)不适用于参数(int)”。
I believed that as per the link http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html , I am allowed to pass -128 to 127 as the arguement. 我相信根据链接http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html ,我可以通过-128到127作为争论。
Please let me know what I am missing? 请让我知道我错过了什么?
You have to cast the integer to byte
: 你必须为整数转换为
byte
:
serialB.setSerializableProp((byte) 1);
Notes: 笔记:
When you do 当你这样做
private byte serializableProp = 10;
10
is a integer, not a binary number. 10
是整数,而不是二进制数。 To specify that the number is a binary you have to use the following syntax: 要指定该数字是二进制文件,您必须使用以下语法:
private byte serializableProp = 0b10; ^^
you are trying to call setSerializableProp()
method with a integer literal.That is giving you compilation error. 你试图用整数文字调用
setSerializableProp()
方法。这给你编译错误。
So down cast the integer literal to byte like below. 因此,将整数文字向下转换为如下所示的字节。
setSerializableProp((byte)1)
serialB.setSerializableProp((byte)1);
这将显式地将整数文字( 1
)转换为一个byte
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.