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"); } } }