Is it possible to use struct-like constructs in Java?

前端 未结 8 1970
时光取名叫无心
时光取名叫无心 2020-12-30 11:15

I\'m considering using Java for a large project but I haven\'t been able to find anything that remotely represented structures in Java. I need to be able to convert network

8条回答
  •  爱一瞬间的悲伤
    2020-12-30 12:08

    You're basically asking whether you can use a C-specific solution to a problem in another language. The answer is, predictably, 'no'.

    However, it is perfectly possible to construct a class that takes a set of bytes in its constructor and constructs an appropriate instance.

    class Foo {
    
      int someField;
      String anotherField;
    
      public Foo(byte[] bytes) {
        someField = someFieldFromBytes(bytes);
        anotherField = anotherFieldFromBytes(bytes);
        etc.
     }
    }
    

    You can ensure there is a one-to-one mapping of class instances to byte arrays. Add a toBytes() method to serialize an instance into bytes.

提交回复
热议问题