是否可以在Java中使用类似结构的构造? [英] Is it possible to use struct-like constructs in Java?

查看:125
本文介绍了是否可以在Java中使用类似结构的构造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑将Java用于大型项目,但我无法在Java中找到任何远程表示结构的东西。我需要能够将网络数据包转换为可以在应用程序中使用的结构/类。

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 packets to structures/classes that can be used in the application.

我知道可以使用 RandomAccessFile 但这种方式 NOT 可以接受。所以我很好奇是否有可能将一组字节强制转换为像我在C中所做的那样的结构。如果这不可能那么我就不能使用Java。

I know that it is possible to use RandomAccessFile but this way is NOT acceptable. So I'm curious if it is possible to "cast" a set of bytes to a structure like I could do in C. If this is not possible then I cannot use Java.

所以我要问的问题是,除了指定对齐方式和数据类型之外,是否可以在不需要额外工作的情况下将对齐数据转换为类?

So the question I'm asking is if it is possible to cast aligned data to a class without any extra effort beyond specifying the alignment and data types?

推荐答案

您基本上是在询问是否可以使用特定于C的解决方案解决另一种语言的问题。可以预见,答案是'不'。

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.
 }
}

你可以确保有类实例到字节数组的一对一映射。添加toBytes()方法将实例序列化为字节。

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.

这篇关于是否可以在Java中使用类似结构的构造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆