Created
July 3, 2020 12:08
-
-
Save zhangjiayin/cfa561d49386058de70209e8508fbdd6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class StructMessage { | |
public void fromBytes(byte[] b) throws IllegalAccessException { | |
ByteBuffer bb = ByteBuffer.wrap(b); | |
for (Field field : this.getClass().getDeclaredFields()) { | |
field.setAccessible(true); | |
Class t = field.getType(); | |
int size = 0; | |
if(t == String.class && field.getName().toLowerCase().equals("name")) { | |
size = 10; | |
} else if( | |
t == Integer.class|| | |
t == Long.class || | |
t == Double.class || | |
t == Float.class || | |
t == Short.class || | |
t == Byte.class | |
) { | |
try { | |
size = (int) t.getField("BYTES").get(null); | |
} catch (NoSuchFieldException e) { | |
e.printStackTrace(); | |
} | |
} | |
if(size == 0) { | |
continue; | |
} | |
byte[] h = new byte[size]; | |
bb.get(h, 0, h.length); | |
final ByteBuffer bc = ByteBuffer.wrap(h); | |
if (t == Integer.class) { | |
bc.order(ByteOrder.LITTLE_ENDIAN); | |
field.set(this, bc.getInt()); | |
} else if (t == Long.class) { | |
bc.order(ByteOrder.LITTLE_ENDIAN); | |
field.set(this, bc.getLong()); | |
} else if (t == Double.class) { | |
bc.order(ByteOrder.LITTLE_ENDIAN); | |
field.set(this, bc.getDouble()); | |
} else if (t == Float.class) { | |
bc.order(ByteOrder.LITTLE_ENDIAN); | |
field.set(this, bc.getFloat()); | |
} else if (t == Short.class) { | |
bc.order(ByteOrder.LITTLE_ENDIAN); | |
field.set(this, bc.getShort()); | |
} else if (t == Byte.class) { | |
bc.order(ByteOrder.LITTLE_ENDIAN); | |
field.set(this, h[0]); | |
} else if (t == String.class) { | |
boolean vEnd = false; | |
int c = 0; | |
for (int i = 0; i < h.length; i++) { | |
if (h[i] == 0) { | |
vEnd = true; | |
} | |
if(h[i] != 0 && !vEnd){ | |
c++; | |
} | |
} | |
byte[] slice = Arrays.copyOfRange(h, 0, c); | |
field.set(this, new String(slice)); | |
} | |
} | |
} | |
abstract void valid() throws IllegalArgumentException; | |
} | |
class StructMessageDetail extends MT5EventsMessage { | |
public Integer header; | |
public Integer sid; | |
public Long time; | |
public Integer size; | |
public String name; | |
@Override | |
public String toString() { | |
return "StructMessageDetail {" + | |
"header=" + header + | |
", sid=" + sid + | |
", time=" + time + | |
", size=" + size + | |
", name='" + name + '\''; | |
} | |
@Override | |
void valid() { | |
if(header==null || header != xxxxx){ | |
throw new IllegalArgumentException("Invalid packet for header"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cpp,java通过tcp 传输结构体转换成java 的类
transfer struct to java from cpp, convert byte array to java Object