你的問題是不是爲你想要什麼非常清楚,但...
你能想出這樣做的像數組的第一個字節一些自定義的協議爲何種類型和其餘的字節是實際的數據。然後您需要編寫代碼將字節[1]通過字節[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對象。不好的一面是,Java對象的序列化會隨着你存儲的對象的進化而變得有些困難(即你刪除方法,字段,編譯w /不同的JDK等)。如果你堅持原語,你應該沒有這個問題。如果你序列化自己的對象,你應該閱讀更多有關兼容和不兼容的更改here。
http://docs.oracle.com/javaee/6/api/javax/mail/util/ByteArrayDataSource.html – Raghunandan
user1249655:問題對我沒有任何意義。我認爲你應該真的考慮你正在努力解決的問題。 Arent你使一件非常簡單的事情變得複雜嗎? –
@ user1249655:向存儲該類型的表中添加另一列。 :) –