开发者

Java equivalent of Python's "construct" library [closed]

开发者 https://www.devze.com 2023-02-15 07:13 出处:网络
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

Closed 3 years ago.

Improve this question

Is there a Java equivalent of Python's "construct" library? I want to write "structs" like so:

message = Struct("message",
    UBInt8("protocol"),
    UBInt16("length"),
    MetaField("data", lambda ctx: ctx["length"])
)

It doesn't have to specifically be a library with some sort of abstraction using the Java language. I mean, it could be a "portable" format, with an API for parsing the documents. I guess this could work out with XML, b开发者_JAVA技巧ut it would be be a lot more ugly.

I realize I could just inter-operate with Python, but I don't want to do that.


I've looked a lot around and all I could find was Ragel (www.complang.org/ragel), that can also produce Java code. It looked too complex for me so I've started some work to port Construct to Java. I suspect it would be easier to make something like that in Scala, Groovy or JavaScript.

Construct on GitHub: https://github.com/MostAwesomeDude/construct

java construct: https://github.com/ZiglioNZ/construct

I've spent a couple of days on it, mostly looking for equivalents of python's expressive classes. The most useful java classes I've found are: java.util.Scanner, java.util.Formatter and java.nio.ByteBuffer. It's a big task so I want to focus on something small like creating simple parsers and formatters for ByteBuffers.

[Update]

I've ported enough code to parse and build some of the protocols that come with Python Construct, such as ethernet, arp and ipv4. Check it out at https://github.com/ZiglioNZ/construct

[Update: new Release]

Java Construct 1.1.2 is now available, see release notes.


You can use DataInput/DataOutput (and their implementations) to convert any set of values from/to a set of bytes. This doesn't give you an object where you can use names to access the individual fields, though - you would have to create such yourself.

It depends a bit on what you want to do - do you have a fixed data format to send/receive on wire, or does this vary from time to time?

0

精彩评论

暂无评论...
验证码 换一张
取 消