问题
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, but 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.
回答1:
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.
回答2:
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?
来源:https://stackoverflow.com/questions/5211604/java-equivalent-of-pythons-construct-library