javastruct()关于java结构体

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

javastruct

A library to treat java objects as C

structs.

Project HomeDownloads Wiki IssuesSource

Search for

HowToUseJavaStruct

This page explains how to use JavaStruct library.

Featured, Phase-Implementation

Updated Feb 4, 2010 by mda...@ Introduction

Struct classes can be used to greatly simplfy network protocol codes of Java applications when working with embedded devices and other applications which uses C style structs.

Instead of manually encoding and decoding messages, JavaStruct allows programmers to treat java classes as c structs.

JavaStruct uses Java 5 annotations to mark Classes and fields as structs. JavaStruct is not the first attempt to provide struct like functionality, Jean-Marie Dautelle's Javolution library also has an excellent struct implementation. But instead of using special classes in Javolution, POJO approach is preferred JavaStruct.

General usage

JavaStruct façade class is used to pack and unpack struct classes. Below is a simple unit test method for checking a struct class. S truct fields hasan order value, because Java JVM specification does not tell anything about order of the class members. They are ordered as their appearance in Sun's implementation but it differs on other JVM's. So every Struct field has to supply an order value. @StructClass

public class Foo{

@StructField(order =0)

public byte b;

@StructField(order =1)

public int i;

}

try{

// Pack the class as a byte buffer

Foo f =new Foo(); //媒体处理器

f.b =(byte)1;

f.i =1;

byte[] b =JavaStruct.pack(f);

// Unpack it into an object

Foo f2 =new Foo();

JavaStruct.unpack(f2, b);

}

catch(StructException e){

}

Struct operations throws a checked S tructException if anything goes wrong.

Struct classes can be used with Streams directly too. Please refer to Photoshop ACB file reader example.

public void read(String acbFile){

try{

FileInputStream fis =new FileInputStream(new File(acbFile));

header =new ACBHeader();

StructUnpacker up =JavaStruct.getUnpacker(fis,ByteOrder.BIG_ENDIAN);

up.readObject(header);

...

Primitives

Using primitives. Note that private and protected fields requires appropriate getter and setter methods. Transient fields are automatically excluded.

@StructClass

public class PublicPrimitives implements Serializable{

@StructField(order =0)

public byte b;

@StructField(order =1)

public char c;

@StructField(order =2)

public short s;

@StructField(order =3)

public int i;

@StructField(order =4)

public long lo;

@StructField(order =5)

protected float f;

@StructField(order =6)

private double d;

相关文档
最新文档