あなたの質問は、あなたが正確に何を望んでいるのかについてはあまり明確ではありませんが...
配列の最初のバイトがどのタイプであるかを示し、残りのバイトが実際のデータであるように、これを行うためのカスタムスキームを考え出すことができます。次に、byte[1] から byte[length-1] までを特定の型に変換するコードを記述する必要があります。私には大変な作業のように思えます。
おそらく、オブジェクトのシリアル化を使用してみます。それは基本的に、あなたがここで求めていることを、最後にカスタムコードなしで行います。
public static void main(String[] args) throws Exception {
String strValue = "hello";
int myInt = 3;
long myLong = 45677;
short myShort = 1;
double myFloat = 4.5;
serializeThenDeserialize(strValue);
serializeThenDeserialize(myInt);
serializeThenDeserialize(myLong);
serializeThenDeserialize(myShort);
serializeThenDeserialize(myFloat);
}
private static void serializeThenDeserialize(Object value) throws Exception {
System.out.println("Input Type is " + value.getClass() + " with value '" + value + "'");
ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteArrayStream);
out.writeObject(value);
out.close();
byte[] objectAsBytes = byteArrayStream.toByteArray();
// Persist here..
// Now lets deserialize the byte array
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(objectAsBytes));
Object deserializedValue = in.readObject();
in.close();
System.out.println("Deserialized Type is " + deserializedValue.getClass() + " with Value '" + deserializedValue + "'");
System.out.println();
}
これを実行すると、希望どおりに動作します。データが返され、型が維持されます。
Input Type is class java.lang.String with value 'hello'
Deserialized Type is class java.lang.String with Value 'hello'
Input Type is class java.lang.Integer with value '3'
Deserialized Type is class java.lang.Integer with Value '3'
Input Type is class java.lang.Long with value '45677'
Deserialized Type is class java.lang.Long with Value '45677'
Input Type is class java.lang.Short with value '1'
Deserialized Type is class java.lang.Short with Value '1'
Input Type is class java.lang.Double with value '4.5'
Deserialized Type is class java.lang.Double with Value '4.5'
これの良いところは、すべての Java オブジェクトに対して機能することです。悪い点は、格納しているオブジェクトが進化するにつれて (つまり、メソッド、フィールドを削除し、別の JDK でコンパイルするなど)、Java オブジェクトのシリアル化が少し面倒になる可能性があることです。ただし、プリミティブに固執する場合は、これで問題はないはずです。独自のオブジェクトをシリアル化する場合は、互換性のある変更と互換性のない変更について詳しく読む必要がありますここ.