hessian

package module
v1.13.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 19, 2026 License: Apache-2.0 Imports: 22 Imported by: 315

README

dubbo-go-hessian2

Build Status codecov GoDoc Go Report Card license


A Go implementation of the Hessian 2.0 serialization protocol, enabling seamless cross-language communication between Go and Java applications. Primarily used by Apache Dubbo-Go for RPC serialization.

Table of Contents

Features

Note: From v1.6.0+, the decoder skips non-existent fields (matching Java hessian behavior). Versions before v1.6.0 returned errors for non-existent fields.

Installation

go get github.com/apache/dubbo-go-hessian2

Requires Go 1.21+.

Quick Start

// Define a struct and implement the POJO interface
type User struct {
    Name string
    Age  int32
}

func (User) JavaClassName() string {
    return "com.example.User"
}

// Register the type before encoding/decoding
hessian.RegisterPOJO(&User{})

// Encode
user := &User{Name: "Alice", Age: 30}
encoder := hessian.NewEncoder()
encoder.Encode(user)
data := encoder.Buffer()

// Decode
obj, _ := hessian.NewDecoder(data).Decode()
decoded := obj.(*User)

Core Concepts

The POJO Interface

Any Go struct that needs to be serialized as a Java object must implement the POJO interface:

type POJO interface {
    JavaClassName() string  // Returns the fully qualified Java class name
}

This establishes the mapping between your Go struct and the corresponding Java class.

Registering Types

Before encoding or decoding custom types, you must register them. This is typically done in an init() function:

func init() {
    // Register a single type
    hessian.RegisterPOJO(&MyStruct{})

    // Register multiple types at once
    hessian.RegisterPOJOs(&TypeA{}, &TypeB{}, &TypeC{})

    // Register with a custom Java class name (overrides JavaClassName())
    hessian.RegisterPOJOMapping("com.example.CustomName", &MyStruct{})
}

If a type is not registered, the decoder will:

  • Default mode: Decode unknown objects as map[interface{}]interface{}
  • Strict mode: Return an error

Type Mapping (Java <-> Go)

Primitive Types
Hessian Type Java Type Go Type
null null nil
binary byte[] []byte
boolean boolean bool
date java.util.Date time.Time
double double float64
int int int32
long long int64
string java.lang.String string
list java.util.List slice
map java.util.Map map
object custom class struct
Java Wrapper Types
Java Type Go Type
java.lang.Integer *int32
java.lang.Long *int64
java.lang.Boolean *bool
java.lang.Short *int16
java.lang.Byte *uint8
java.lang.Float *float32
java.lang.Double *float64
java.lang.Character *hessian.Rune
Extended Types
Java Type Go Type / Package
java.math.BigDecimal github.com/dubbogo/gost/math/big Decimal
java.math.BigInteger github.com/dubbogo/gost/math/big Integer
java.sql.Date github.com/apache/dubbo-go-hessian2/java_sql_time Date
java.sql.Time github.com/apache/dubbo-go-hessian2/java_sql_time Time
java.util.UUID github.com/apache/dubbo-go-hessian2/java_util UUID
java.util.Locale github.com/apache/dubbo-go-hessian2/java_util Locale
Java 8 time types (LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Instant, Duration, Period, etc.) github.com/apache/dubbo-go-hessian2/java8_time

Tip: Avoid defining objects that only exist in one language. Use error codes/messages instead of Java exceptions for cross-language communication.

API Reference

Encoder
// Create a new encoder
encoder := hessian.NewEncoder()

// Encode a value (primitives, slices, maps, structs, etc.)
err := encoder.Encode(value)

// Get the encoded bytes
data := encoder.Buffer()

// Reset encoder state for reuse
encoder.Clean()

// Reset encoder state but reuse the underlying buffer
encoder.ReuseBufferClean()

Special encoding methods:

// Encode a map as a typed Java object using "_class" key in the map
encoder.EncodeMapClass(map[string]interface{}{"_class": "com.example.Foo", "name": "bar"})

// Encode a map as a specific Java class
encoder.EncodeMapAsClass("com.example.Foo", map[string]interface{}{"name": "bar"})
Decoder
// Standard decoder
decoder := hessian.NewDecoder(data)

// Strict mode - returns error for unregistered types
decoder := hessian.NewStrictDecoder(data)

// Decode the next value
obj, err := decoder.Decode()

// Reset decoder with new data (for reuse with object pools)
decoder.Reset(newData)

Decoder modes:

Constructor Behavior
NewDecoder(data) Decodes unknown objects as maps
NewStrictDecoder(data) Returns error for unregistered objects
NewDecoderWithSkip(data) Skips non-existent fields
NewCheapDecoderWithSkip(data) Poolable decoder, use with Reset()
Registration Functions
hessian.RegisterPOJO(&MyStruct{})                         // Register a POJO type
hessian.RegisterPOJOs(&A{}, &B{})                         // Register multiple POJOs
hessian.RegisterPOJOMapping("com.example.Name", &Struct{}) // Register with custom Java class name
hessian.RegisterJavaEnum(&MyEnum{})                        // Register a Java enum type
hessian.UnRegisterPOJOs(&A{}, &B{})                        // Unregister POJOs
hessian.SetCollectionSerialize(&MyHashSet{})               // Register a Java collection type
hessian.SetSerializer("com.example.Foo", &FooSerializer{}) // Register a custom serializer
Configuration Functions
// Change the struct tag used for field name mapping (default: "hessian")
hessian.SetTagIdentifier("json")

// Look up a registered custom serializer
serializer, ok := hessian.GetSerializer("com.example.Foo")

// Find class info in the decoder
classInfo := hessian.FindClassInfo("com.example.Foo")

Usage Examples

Encoding and Decoding Custom Objects
type Circular struct {
    Value
    Previous *Circular
    Next     *Circular
}

type Value struct {
    Num int
}

func (Circular) JavaClassName() string {
    return "com.company.Circular"
}

func init() {
    hessian.RegisterPOJO(&Circular{})
}

// Encode
c := &Circular{}
c.Num = 12345
c.Previous = c  // circular reference - handled automatically
c.Next = c

e := hessian.NewEncoder()
if err := e.Encode(c); err != nil {
    panic(err)
}
data := e.Buffer()

// Decode
obj, err := hessian.NewDecoder(data).Decode()
if err != nil {
    panic(err)
}
circular := obj.(*Circular)
fmt.Println(circular.Num) // 12345
Customizing Field Names with Tags

The encoder converts Go field names to lowerCamelCase by default. Use the hessian tag to override:

type MyUser struct {
    UserFullName      string `hessian:"user_full_name"` // encoded as "user_full_name"
    FamilyPhoneNumber string                            // encoded as "familyPhoneNumber" (default)
}

func (MyUser) JavaClassName() string {
    return "com.company.myuser"
}
Decoding Field Name Matching Rules

When decoding, fields are matched in the following order:

  1. Tag match - matches the hessian tag value
  2. lowerCamelCase - e.g., mobilePhone matches MobilePhone
  3. Exact case - e.g., MobilePhone matches MobilePhone
  4. Lowercase - e.g., mobilephone matches MobilePhone
type MyUser struct {
    MobilePhone string `hessian:"mobile-phone"`
}
// Incoming field "mobile-phone" -> matched via tag (rule 1)
// Incoming field "mobilePhone"  -> matched via lowerCamelCase (rule 2)
// Incoming field "MobilePhone"  -> matched via exact case (rule 3)
// Incoming field "mobilephone"  -> matched via lowercase (rule 4)
Using a Custom Tag Identifier

Use SetTagIdentifier to read field names from a different struct tag (e.g., json):

hessian.SetTagIdentifier("json")

type MyUser struct {
    UserFullName      string `json:"user_full_name"`
    FamilyPhoneNumber string
}

func (MyUser) JavaClassName() string {
    return "com.company.myuser"
}
Specifying Java Parameter Types (Inheritance)

When a Java method expects a parent class but you send a subclass, implement the Param interface:

Java side:

public abstract class User {}

public class MyUser extends User implements Serializable {
    private String userFullName;
    private String familyPhoneNumber;
}

public interface UserProvider {
    String GetUser(User user);  // accepts parent type
}

Go side:

type MyUser struct {
    UserFullName      string `hessian:"userFullName"`
    FamilyPhoneNumber string
}

func (m *MyUser) JavaClassName() string {
    return "com.company.MyUser"
}

// JavaParamName tells the encoder to use the parent class name in the method signature
func (m *MyUser) JavaParamName() string {
    return "com.company.User"
}
Working with Java Collections

Map a Java collection class (e.g., HashSet) to a Go struct:

type JavaHashSet struct {
    value []interface{}
}

func (j *JavaHashSet) Get() []interface{}       { return j.value }
func (j *JavaHashSet) Set(v []interface{})      { j.value = v }
func (j *JavaHashSet) JavaClassName() string    { return "java.util.HashSet" }

func init() {
    hessian.SetCollectionSerialize(&JavaHashSet{})
}

Without this registration, Java collections are decoded as []interface{}.

Working with Java Enums
type Color int32

const (
    RED   Color = 0
    GREEN Color = 1
    BLUE  Color = 2
)

var colorNames = map[Color]string{
    RED: "RED", GREEN: "GREEN", BLUE: "BLUE",
}
var colorValues = map[string]Color{
    "RED": RED, "GREEN": GREEN, "BLUE": BLUE,
}

func (c Color) JavaClassName() string   { return "com.example.Color" }
func (c Color) String() string          { return colorNames[c] }
func (c Color) EnumValue(s string) hessian.JavaEnum {
    return hessian.JavaEnum(colorValues[s])
}

func init() {
    hessian.RegisterJavaEnum(RED)
}
Custom Serializer

Implement the Serializer interface for full control over encoding/decoding:

type MySerializer struct{}

func (s *MySerializer) EncObject(encoder *hessian.Encoder, obj hessian.POJO) error {
    // Custom encoding logic
    return nil
}

func (s *MySerializer) DecObject(decoder *hessian.Decoder, typ reflect.Type, cls *hessian.ClassInfo) (interface{}, error) {
    // Custom decoding logic
    return nil, nil
}

func init() {
    hessian.SetSerializer("com.example.MyClass", &MySerializer{})
}
Strict Mode

By default, unregistered objects are decoded as maps. Use strict mode to get errors instead:

decoder := hessian.NewDecoder(data)
decoder.Strict = true  // returns error for unregistered types

// Or use the convenience constructor:
decoder = hessian.NewStrictDecoder(data)
Reusing Encoder/Decoder (Object Pool)

For high-performance scenarios, reuse encoder/decoder instances:

// Encoder reuse
encoder := hessian.NewEncoder()
encoder.Encode(obj1)
data1 := encoder.Buffer()

encoder.Clean()  // or encoder.ReuseBufferClean() to keep the buffer
encoder.Encode(obj2)
data2 := encoder.Buffer()

// Decoder reuse (poolable decoder)
decoder := hessian.NewCheapDecoderWithSkip(data1)
obj1, _ := decoder.Decode()

decoder.Reset(data2)  // reuse with new data
obj2, _ := decoder.Decode()

Struct Inheritance

Go struct embedding is supported for modeling Java inheritance:

type Animal struct {
    Name string
}

func (Animal) JavaClassName() string { return "com.example.Animal" }

type Dog struct {
    Animal          // embedded parent struct
    Breed  string
}

func (Dog) JavaClassName() string { return "com.example.Dog" }

Avoid these patterns:

  1. Duplicate field names across parents - ambiguous field resolution:

    type A struct { Name string }
    type B struct { Name string }
    type C struct { A; B }  // which Name?
    
  2. Pointer embedding - nil parent at initialization, not supported:

    type Dog struct {
        *Animal  // will be nil in Dog{}, not supported
    }
    

Tools

gen-go-enum

A code generation tool for creating Go enum types compatible with Java enums. See tools/gen-go-enum/README.md for details.

Reference

Documentation

Overview

pack/unpack fixed length variable

Index

Constants

View Source
const (
	TAG_READ        = int32(-1)
	ASCII_GAP       = 32
	CHUNK_SIZE      = 4096
	BC_BINARY       = byte('B') // final chunk
	BC_BINARY_CHUNK = byte('A') // non-final chunk

	BC_BINARY_DIRECT  = byte(0x20) // 1-byte length binary
	BINARY_DIRECT_MAX = byte(0x0f)
	BC_BINARY_SHORT   = byte(0x34) // 2-byte length binary
	BINARY_SHORT_MAX  = 0x3ff      // 0-1023 binary

	BC_DATE        = byte(0x4a) // 64-bit millisecond UTC date
	BC_DATE_MINUTE = byte(0x4b) // 32-bit minute UTC date

	BC_DOUBLE = byte('D') // IEEE 64-bit double

	BC_DOUBLE_ZERO  = byte(0x5b)
	BC_DOUBLE_ONE   = byte(0x5c)
	BC_DOUBLE_BYTE  = byte(0x5d)
	BC_DOUBLE_SHORT = byte(0x5e)
	BC_DOUBLE_MILL  = byte(0x5f)

	BC_FALSE = byte('F') // boolean false

	BC_INT = byte('I') // 32-bit int

	INT_DIRECT_MIN = -0x10
	INT_DIRECT_MAX = byte(0x2f)
	BC_INT_ZERO    = byte(0x90)

	INT_BYTE_MIN     = -0x800
	INT_BYTE_MAX     = 0x7ff
	BC_INT_BYTE_ZERO = byte(0xc8)

	BC_END = byte('Z')

	INT_SHORT_MIN     = -0x40000
	INT_SHORT_MAX     = 0x3ffff
	BC_INT_SHORT_ZERO = byte(0xd4)

	BC_LIST_VARIABLE         = byte(0x55)
	BC_LIST_FIXED            = byte('V')
	BC_LIST_VARIABLE_UNTYPED = byte(0x57)
	BC_LIST_FIXED_UNTYPED    = byte(0x58)

	BC_LIST_DIRECT         = byte(0x70)
	BC_LIST_DIRECT_UNTYPED = byte(0x78)
	LIST_DIRECT_MAX        = byte(0x7)

	BC_LONG         = byte('L') // 64-bit signed integer
	LONG_DIRECT_MIN = -0x08
	LONG_DIRECT_MAX = byte(0x0f)
	BC_LONG_ZERO    = byte(0xe0)

	LONG_BYTE_MIN     = -0x800
	LONG_BYTE_MAX     = 0x7ff
	BC_LONG_BYTE_ZERO = byte(0xf8)

	LONG_SHORT_MIN     = -0x40000
	LONG_SHORT_MAX     = 0x3ffff
	BC_LONG_SHORT_ZERO = byte(0x3c)

	BC_LONG_INT = byte(0x59)

	BC_MAP         = byte('M')
	BC_MAP_UNTYPED = byte('H')

	BC_NULL = byte('N') // x4e

	BC_OBJECT     = byte('O')
	BC_OBJECT_DEF = byte('C')

	BC_OBJECT_DIRECT  = byte(0x60)
	OBJECT_DIRECT_MAX = byte(0x0f)

	BC_REF = byte(0x51)

	BC_STRING       = byte('S') // final string
	BC_STRING_CHUNK = byte('R') // non-final string

	BC_STRING_DIRECT  = byte(0x00)
	STRING_DIRECT_MAX = byte(0x1f)
	BC_STRING_SHORT   = byte(0x30)
	STRING_SHORT_MAX  = 0x3ff

	BC_TRUE = byte('T')

	P_PACKET_CHUNK = byte(0x4f)
	P_PACKET       = byte('P')

	P_PACKET_DIRECT   = byte(0x80)
	PACKET_DIRECT_MAX = byte(0x7f)

	P_PACKET_SHORT   = byte(0x70)
	PACKET_SHORT_MAX = 0xfff
	ARRAY_STRING     = "[string"
	ARRAY_INT        = "[int"
	ARRAY_DOUBLE     = "[double"
	ARRAY_FLOAT      = "[float"
	ARRAY_BOOL       = "[boolean"
	ARRAY_LONG       = "[long"

	PATH_KEY      = "path"
	GROUP_KEY     = "group"
	INTERFACE_KEY = "interface"
	VERSION_KEY   = "version"
	TIMEOUT_KEY   = "timeout"

	STRING_NIL   = ""
	STRING_TRUE  = "true"
	STRING_FALSE = "false"
	STRING_ZERO  = "0.0"
	STRING_ONE   = "1.0"
)

constants

View Source
const (
	Response_OK                byte = 20
	Response_CLIENT_TIMEOUT    byte = 30
	Response_SERVER_TIMEOUT    byte = 31
	Response_BAD_REQUEST       byte = 40
	Response_BAD_RESPONSE      byte = 50
	Response_SERVICE_NOT_FOUND byte = 60
	Response_SERVICE_ERROR     byte = 70
	Response_SERVER_ERROR      byte = 80
	Response_CLIENT_ERROR      byte = 90

	// According to "java dubbo" There are two cases of response:
	// 		1. with attachments
	// 		2. no attachments
	RESPONSE_WITH_EXCEPTION                  int32 = 0
	RESPONSE_VALUE                           int32 = 1
	RESPONSE_NULL_VALUE                      int32 = 2
	RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS int32 = 3
	RESPONSE_VALUE_WITH_ATTACHMENTS          int32 = 4
	RESPONSE_NULL_VALUE_WITH_ATTACHMENTS     int32 = 5
)

Response related consts

View Source
const (
	// header length.
	HEADER_LENGTH = 16

	// magic header
	MAGIC      = uint16(0xdabb)
	MAGIC_HIGH = byte(0xda)
	MAGIC_LOW  = byte(0xbb)

	// message flag.
	FLAG_REQUEST = byte(0x80)
	FLAG_TWOWAY  = byte(0x40)
	FLAG_EVENT   = byte(0x20) // for heartbeat
	SERIAL_MASK  = 0x1f

	DUBBO_VERSION                          = "2.5.4"
	DUBBO_VERSION_KEY                      = "dubbo"
	DEFAULT_DUBBO_PROTOCOL_VERSION         = "2.0.2" // Dubbo RPC protocol version, for compatibility, it must not be between 2.0.10 ~ 2.6.2
	LOWEST_VERSION_FOR_RESPONSE_ATTACHMENT = 2000200
	DEFAULT_LEN                            = 8388608 // 8 * 1024 * 1024 default body max length
)

*

  • the dubbo protocol header length is 16 Bytes.
  • the first 2 Bytes is magic code '0xdabb'
  • the next 1 Byte is message flags, in which its 16-20 bit is serial id, 21 for event, 22 for two way, 23 for request/response flag
  • the next 1 Bytes is response state.
  • the next 8 Bytes is package DI.
  • the next 4 Bytes is package length. *
View Source
const (
	JAVA_IDENT_REGEX = "(?:[_$a-zA-Z][_$a-zA-Z0-9]*)"
	CLASS_DESC       = "(?:L" + JAVA_IDENT_REGEX + "(?:\\/" + JAVA_IDENT_REGEX + ")*;)"
	ARRAY_DESC       = "(?:\\[+(?:(?:[VZBCDFIJS])|" + CLASS_DESC + "))"
	DESC_REGEX       = "(?:(?:[VZBCDFIJS])|" + CLASS_DESC + "|" + ARRAY_DESC + ")"
)

regular

View Source
const (
	// Zero : byte zero
	Zero = byte(0x00)
)

Variables

View Source
var (
	DubboRequestHeaderBytesTwoWay = [HEADER_LENGTH]byte{MAGIC_HIGH, MAGIC_LOW, FLAG_REQUEST | FLAG_TWOWAY}
	DubboRequestHeaderBytes       = [HEADER_LENGTH]byte{MAGIC_HIGH, MAGIC_LOW, FLAG_REQUEST}
	DubboResponseHeaderBytes      = [HEADER_LENGTH]byte{MAGIC_HIGH, MAGIC_LOW, Zero, Response_OK}
	DubboRequestHeartbeatHeader   = [HEADER_LENGTH]byte{MAGIC_HIGH, MAGIC_LOW, FLAG_REQUEST | FLAG_TWOWAY | FLAG_EVENT}
	DubboResponseHeartbeatHeader  = [HEADER_LENGTH]byte{MAGIC_HIGH, MAGIC_LOW, FLAG_EVENT}
)

Dubbo request response related consts

View Source
var (
	ErrHeaderNotEnough = perrors.New("header buffer too short")
	ErrBodyNotEnough   = perrors.New("body buffer too short")
	ErrJavaException   = perrors.New("got java exception")
	ErrIllegalPackage  = perrors.New("illegal package!")
)

Error part

View Source
var (
	ErrNotEnoughBuf    = perrors.Errorf("not enough buf")
	ErrIllegalRefIndex = perrors.Errorf("illegal ref index")
)

Error part

View Source
var DescRegex, _ = regexp.Compile(DESC_REGEX)

DescRegex ...

View Source
var NilValue = reflect.Zero(reflect.TypeOf((*interface{})(nil)).Elem())
View Source
var ZeroDate = time.Time{}

/////////////////////////////////////// Date ///////////////////////////////////////

Functions

func AddrEqual

func AddrEqual(x, y interface{}) bool

AddrEqual compares addrs

func ConvertSliceValueType

func ConvertSliceValueType(destTyp reflect.Type, v reflect.Value) (reflect.Value, error)

ConvertSliceValueType convert to slice of destination type

func EncNull added in v1.7.0

func EncNull(b []byte) []byte

/////////////////////////////////////// Null ///////////////////////////////////////

func EnsureInterface

func EnsureInterface(in interface{}, err error) (interface{}, error)

EnsureInterface get value of reflect.Value return original value if not reflect.Value

func EnsurePackValue

func EnsurePackValue(in interface{}) reflect.Value

EnsurePackValue pack the interface with value

func EnsureRawAny added in v1.10.2

func EnsureRawAny(in interface{}) interface{}

EnsureRawAny unpack if in is a reflect.Value or a ref holder.

func EnsureRawValue

func EnsureRawValue(in interface{}) reflect.Value

EnsureRawValue pack the interface with value, and make sure it's not a ref holder

func GetGoType added in v1.9.5

func GetGoType(o interface{}) string

GetGoType get the raw go type name with package.

func PackFloat64

func PackFloat64(v float64) []byte

PackFloat64 packs float64 to byte array [10].pack('G').bytes => [64, 36, 0, 0, 0, 0, 0, 0] PackFloat64 invokes go's official math library function Float64bits.

func PackInt8

func PackInt8(v int8, b []byte) []byte

PackInt8 packs int to byte array

func PackInt16

func PackInt16(v int16) []byte

PackInt16 packs int16 to byte array [10].pack('N').bytes => [0, 0, 0, 10]

func PackInt32

func PackInt32(v int32) []byte

PackInt32 packs int32 to byte array [10].pack('N').bytes => [0, 0, 0, 10]

func PackInt64

func PackInt64(v int64) []byte

PackInt64 packs int64 to byte array [10].pack('q>').bytes => [0, 0, 0, 0, 0, 0, 0, 10]

func PackPtr

func PackPtr(v reflect.Value) reflect.Value

PackPtr pack a Ptr value

func PackPtrInterface added in v1.9.5

func PackPtrInterface(s interface{}, value reflect.Value) interface{}

PackPtrInterface pack struct interface to pointer interface

func PackUint16

func PackUint16(v uint16) []byte

PackUint16 packs uint16 to byte array [10].pack('N').bytes => [0, 0, 0, 10]

func RegisterJavaEnum

func RegisterJavaEnum(o POJOEnum) int

RegisterJavaEnum Register a value type JavaEnum variable.

func RegisterPOJO

func RegisterPOJO(o POJO) int

RegisterPOJO Register a POJO instance. The return value is -1 if @o has been registered.

func RegisterPOJOMapping added in v1.7.0

func RegisterPOJOMapping(javaClassName string, o interface{}) int

RegisterPOJOMapping Register a POJO instance. The return value is -1 if @o has been registered.

func RegisterPOJOs

func RegisterPOJOs(os ...POJO) []int

RegisterPOJOs register a POJO instance arr @os. The return value is @os's mathching index array, in which "-1" means its matching POJO has been registered.

func SetCollectionSerialize added in v1.5.0

func SetCollectionSerialize(collection JavaCollectionObject)

func SetJavaSqlTimeSerialize added in v1.6.3

func SetJavaSqlTimeSerialize(time java_sql_time.JavaSqlTime)

SetJavaSqlTimeSerialize register serializer for java.sql.Time & java.sql.Date

func SetSerializer

func SetSerializer(javaClassName string, codec Serializer)

func SetSlice

func SetSlice(dest reflect.Value, objects interface{}) error

SetSlice set value into slice object

func SetTagIdentifier

func SetTagIdentifier(s string)

SetTagIdentifier for customize struct filed tag of hessian, your can use it like:

hessian.SetTagIdentifier("json")
type MyUser struct {
	UserFullName      string   `json:"user_full_name"`
	FamilyPhoneNumber string   // default convert to => familyPhoneNumber
}
var user MyUser
hessian.NewEncoder().Encode(user)

func SetValue

func SetValue(dest, v reflect.Value)

SetValue set the value to dest. It will auto check the Ptr pack level and unpack/pack to the right level. It makes sure success to set value

func SetValueToPtrDest added in v1.12.2

func SetValueToPtrDest(dest reflect.Value, v reflect.Value)

SetValueToPtrDest set the raw value to a pointer dest.

func Slice

func Slice(s string) []byte

/////////////////////////////////////// String /////////////////////////////////////// Slice convert string to byte slice

func SprintHex

func SprintHex(b []byte) (rs string)

SprintHex converts the []byte to a Hex string.

func UnRegisterPOJOs added in v1.7.0

func UnRegisterPOJOs(os ...POJO) []int

UnRegisterPOJOs unregister POJO instances. It is easy for test.

func UnpackFloat64

func UnpackFloat64(b []byte) float64

UnpackFloat64 unpacks float64 from byte array Double (0,8).unpack('G)

func UnpackInt16

func UnpackInt16(b []byte) int16

UnpackInt16 unpacks int16 from byte array (0,2).unpack('n')

func UnpackInt32

func UnpackInt32(b []byte) int32

UnpackInt32 unpacks int32 from byte array (0,4).unpack('N')

func UnpackInt64

func UnpackInt64(b []byte) int64

UnpackInt64 unpacks int64 from byte array long (0,8).unpack('q>')

func UnpackPtr

func UnpackPtr(v reflect.Value) reflect.Value

UnpackPtr unpack pointer value to original value

func UnpackPtrType

func UnpackPtrType(typ reflect.Type) reflect.Type

UnpackPtrType unpack pointer type to original type

func UnpackPtrValue

func UnpackPtrValue(v reflect.Value) reflect.Value

UnpackPtrValue unpack pointer value to original value return the pointer if its elem is zero value, because lots of operations on zero value is invalid

func UnpackToRootAddressableValue added in v1.12.2

func UnpackToRootAddressableValue(v reflect.Value) reflect.Value

UnpackToRootAddressableValue unpack pointer value to the root addressable value.

func UnpackType added in v1.12.2

func UnpackType(typ reflect.Type) (reflect.Type, int)

UnpackType unpack pointer type to original type and return the pointer depth.

func UnpackUint16

func UnpackUint16(b []byte) uint16

UnpackUint16 unpacks int16 from byte array (0,2).unpack('n')

Types

type BooleanArray added in v1.9.4

type BooleanArray struct {
	Values []bool
}

BooleanArray Boolean[] Deprecated: it will not be supported in next major version, being replaced by a slice type instead.

func (*BooleanArray) Get added in v1.9.4

func (ba *BooleanArray) Get() []interface{}

nolint

func (*BooleanArray) JavaClassName added in v1.9.4

func (*BooleanArray) JavaClassName() string

nolint

func (*BooleanArray) Set added in v1.9.4

func (ba *BooleanArray) Set(vs []interface{})

nolint

type ByteArray added in v1.9.4

type ByteArray struct {
	Values []uint8
}

ByteArray Byte[] Deprecated: it will not be supported in next major version, being replaced by a slice type instead.

func (*ByteArray) Get added in v1.9.4

func (ba *ByteArray) Get() []interface{}

nolint

func (*ByteArray) JavaClassName added in v1.9.4

func (*ByteArray) JavaClassName() string

nolint

func (*ByteArray) Set added in v1.9.4

func (ba *ByteArray) Set(vs []interface{})

nolint

type CharacterArray added in v1.9.4

type CharacterArray struct {
	Values string
}

CharacterArray Character[] Deprecated: it will not be supported in next major version, being replaced by a slice type instead.

func (*CharacterArray) Get added in v1.9.4

func (ca *CharacterArray) Get() []interface{}

nolint

func (*CharacterArray) JavaClassName added in v1.9.4

func (*CharacterArray) JavaClassName() string

nolint

func (*CharacterArray) Set added in v1.9.4

func (ca *CharacterArray) Set(vs []interface{})

nolint

type ClassInfo added in v1.11.0

type ClassInfo struct {
	// contains filtered or unexported fields
}

type DecimalSerializer

type DecimalSerializer struct{}

func (DecimalSerializer) DecObject

func (DecimalSerializer) DecObject(d *Decoder, typ reflect.Type, cls *ClassInfo) (interface{}, error)

func (DecimalSerializer) EncObject

func (DecimalSerializer) EncObject(e *Encoder, v POJO) error

type Decoder

type Decoder struct {

	// In strict mode, a class data can be decoded only when the class is registered, otherwise error returned.
	// In non-strict mode, a class data will be decoded to a map when the class is not registered.
	// The default is non-strict mode, user can change it as required.
	Strict bool
	// contains filtered or unexported fields
}

Decoder struct Note: Decoder instances are not goroutine-safe. If you need to use a Decoder concurrently across multiple goroutines, you must add external synchronization.

func NewCheapDecoderWithSkip added in v1.6.0

func NewCheapDecoderWithSkip(b []byte) *Decoder

NewCheapDecoderWithSkip generate a decoder instance with skip, only for cache pool, before decode Reset should be called. For example, with pooling use, will effectively improve performance

	var hessianPool = &sync.Pool{
		New: func() interface{} {
			return hessian.NewCheapDecoderWithSkip([]byte{})
		},
	}

	decoder := hessianPool.Get().(*hessian.Decoder)
	fill decode data
	decoder.Reset(data[:])
 decode anything ...
	hessianPool.Put(decoder)

func NewDecoder

func NewDecoder(b []byte) *Decoder

NewDecoder generate a decoder instance

func NewDecoderSize added in v1.6.0

func NewDecoderSize(b []byte, size int) *Decoder

NewDecoderSize generate a decoder instance.

func NewDecoderWithSkip added in v1.3.0

func NewDecoderWithSkip(b []byte) *Decoder

NewDecoderWithSkip generate a decoder instance with skip.

func NewStrictDecoder added in v1.11.0

func NewStrictDecoder(b []byte) *Decoder

NewStrictDecoder generates a strict mode decoder instance. In strict mode, all target class must be registered.

func (*Decoder) Buffered added in v1.6.0

func (d *Decoder) Buffered() int

func (*Decoder) Clean added in v1.8.0

func (d *Decoder) Clean()

Clean clean the Decoder (room) for a new object decoding. Notice it won't reset reader buffer and will continue to read data from it.

func (*Decoder) Decode

func (d *Decoder) Decode() (interface{}, error)

Decode parse hessian data, and ensure the reflection value unpacked

func (*Decoder) DecodeValue

func (d *Decoder) DecodeValue() (interface{}, error)

DecodeValue parse hessian data, the return value maybe a reflection value when it's a map, list, object, or ref.

func (*Decoder) Discard added in v1.8.0

func (d *Decoder) Discard(n int) (int, error)

Discard skips the next n bytes

func (*Decoder) FindClassInfo added in v1.11.0

func (d *Decoder) FindClassInfo(javaName string) *ClassInfo

FindClassInfo find ClassInfo for the given name in decoder class info list.

func (*Decoder) ReadByte added in v1.8.0

func (d *Decoder) ReadByte() (byte, error)

ReadByte read a byte from Decoder, advance the ptr

func (*Decoder) Reset added in v1.6.0

func (d *Decoder) Reset(b []byte) *Decoder

type DoubleArray added in v1.9.4

type DoubleArray struct {
	Values []float64
}

DoubleArray Double[] Deprecated: it will not be supported in next major version, being replaced by a slice type instead.

func (*DoubleArray) Get added in v1.9.4

func (da *DoubleArray) Get() []interface{}

nolint

func (*DoubleArray) JavaClassName added in v1.9.4

func (*DoubleArray) JavaClassName() string

nolint

func (*DoubleArray) Set added in v1.9.4

func (da *DoubleArray) Set(vs []interface{})

nolint

type Encoder

type Encoder struct {
	// contains filtered or unexported fields
}

nil bool int8 int32 int64 float32 float64 time.Time string []byte []interface{} map[interface{}]interface{} array object struct Encoder struct

func NewEncoder

func NewEncoder() *Encoder

NewEncoder generate an encoder instance

func (*Encoder) Append

func (e *Encoder) Append(buf []byte)

Append byte arr to encoder buffer

func (*Encoder) Buffer

func (e *Encoder) Buffer() []byte

Buffer returns byte buffer

func (*Encoder) Clean added in v1.8.0

func (e *Encoder) Clean()

Clean clean the Encoder (room) for a new object encoding.

func (*Encoder) Encode

func (e *Encoder) Encode(v interface{}) error

Encode If @v can not be encoded, the return value is nil. At present only struct may can not be encoded.

func (*Encoder) EncodeMapAsClass added in v1.11.0

func (e *Encoder) EncodeMapAsClass(className string, m map[string]interface{}) error

EncodeMapAsClass encode a map as object of given class name.

func (*Encoder) EncodeMapAsObject added in v1.11.0

func (e *Encoder) EncodeMapAsObject(clsDef *ClassInfo, m map[string]interface{}) error

EncodeMapAsObject encode a map as the given class defined object. Sometimes a class may not being registered in hessian, but it can be decoded from serialized data, and the ClassInfo can be found in Decoder by calling Decoder.FindClassInfo.

func (*Encoder) EncodeMapClass added in v1.11.0

func (e *Encoder) EncodeMapClass(m map[string]interface{}) error

EncodeMapClass encode a map as object, which MUST contains a key _class and its value is the target class name.

func (*Encoder) ReuseBufferClean added in v1.9.3

func (e *Encoder) ReuseBufferClean()

ReuseBufferClean reuse the Encoder for a new object encoding. it reuse allocated buffer and reduce memory-allocation.

type FloatArray added in v1.9.4

type FloatArray struct {
	Values []float32
}

FloatArray Float[] Deprecated: it will not be supported in next major version, being replaced by a slice type instead.

func (*FloatArray) Get added in v1.9.4

func (fa *FloatArray) Get() []interface{}

nolint

func (*FloatArray) JavaClassName added in v1.9.4

func (*FloatArray) JavaClassName() string

nolint

func (*FloatArray) Set added in v1.9.4

func (fa *FloatArray) Set(vs []interface{})

nolint

type IntegerArray added in v1.9.4

type IntegerArray struct {
	Values []int32
}

IntegerArray Integer[]. Deprecated: it will not be supported in next major version, being replaced by a slice type instead.

func (*IntegerArray) Get added in v1.9.4

func (ia *IntegerArray) Get() []interface{}

nolint

func (*IntegerArray) JavaClassName added in v1.9.4

func (*IntegerArray) JavaClassName() string

nolint

func (*IntegerArray) Set added in v1.9.4

func (ia *IntegerArray) Set(vs []interface{})

nolint

type IntegerSerializer added in v1.4.0

type IntegerSerializer struct{}

func (IntegerSerializer) DecObject added in v1.4.0

func (IntegerSerializer) DecObject(d *Decoder, typ reflect.Type, cls *ClassInfo) (interface{}, error)

func (IntegerSerializer) EncObject added in v1.4.0

func (IntegerSerializer) EncObject(e *Encoder, v POJO) error

type JavaCollectionObject added in v1.5.0

type JavaCollectionObject interface {
	Get() []interface{}
	Set([]interface{})
	JavaClassName() string
}

type JavaCollectionSerializer added in v1.5.0

type JavaCollectionSerializer struct{}

func (JavaCollectionSerializer) DecObject added in v1.5.0

func (JavaCollectionSerializer) DecObject(d *Decoder, typ reflect.Type, cls *ClassInfo) (interface{}, error)

func (JavaCollectionSerializer) EncObject added in v1.5.0

func (JavaCollectionSerializer) EncObject(e *Encoder, vv POJO) error

type JavaEnum

type JavaEnum int32

JavaEnum type

const (
	InvalidJavaEnum JavaEnum = -1

	ClassKey = "_class"
)

invalid consts

type JavaEnumClass

type JavaEnumClass struct {
	// contains filtered or unexported fields
}

JavaEnumClass struct

type JavaSqlTimeSerializer added in v1.6.3

type JavaSqlTimeSerializer struct{}

JavaSqlTimeSerializer used to encode & decode java.sql.Time & java.sql.Date

func (JavaSqlTimeSerializer) DecObject added in v1.6.3

func (JavaSqlTimeSerializer) DecObject(d *Decoder, typ reflect.Type, cls *ClassInfo) (interface{}, error)

nolint

func (JavaSqlTimeSerializer) EncObject added in v1.6.3

func (JavaSqlTimeSerializer) EncObject(e *Encoder, vv POJO) error

nolint

type LongArray added in v1.9.4

type LongArray struct {
	Values []int64
}

LongArray Long[] Deprecated: it will not be supported in next major version, being replaced by a slice type instead.

func (*LongArray) Get added in v1.9.4

func (ba *LongArray) Get() []interface{}

nolint

func (*LongArray) JavaClassName added in v1.9.4

func (*LongArray) JavaClassName() string

nolint

func (*LongArray) Set added in v1.9.4

func (ba *LongArray) Set(vs []interface{})

nolint

type Object

type Object interface{}

Object is equal to Object of java When encoding

type POJO

type POJO interface {
	JavaClassName() string // got a go struct's Java Class package name which should be a POJO class.
}

POJO interface !!! Pls attention that Every field name should be upper case. Otherwise the app may panic.

type POJOEnum

type POJOEnum interface {
	POJO
	String() string
	EnumValue(string) JavaEnum
}

POJOEnum enum for POJO

type POJORegistry

type POJORegistry struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

POJORegistry pojo registry struct

type Param added in v1.10.0

type Param interface {
	POJO
	JavaParamName() string
}

Param interface !!! Pls attention that Every field name should be upper case. specifies the Java method parameter type. if this interface is not implemented, the pojo javaClassName is used as the method parameter type by default

type Rune added in v1.12.0

type Rune rune

Rune is an alias for rune, so that to get the correct runtime type of rune. The runtime type of rune is int32, which is not expected.

type Serializer

type Serializer interface {
	EncObject(*Encoder, POJO) error
	DecObject(*Decoder, reflect.Type, *ClassInfo) (interface{}, error)
}

func GetSerializer

func GetSerializer(javaClassName string) (Serializer, bool)

type ShortArray added in v1.9.4

type ShortArray struct {
	Values []int16
}

ShortArray Short[] Deprecated: it will not be supported in next major version, being replaced by a slice type instead.

func (*ShortArray) Get added in v1.9.4

func (sa *ShortArray) Get() []interface{}

nolint

func (*ShortArray) JavaClassName added in v1.9.4

func (*ShortArray) JavaClassName() string

nolint

func (*ShortArray) Set added in v1.9.4

func (sa *ShortArray) Set(vs []interface{})

nolint

type TypeRefs

type TypeRefs struct {
	// contains filtered or unexported fields
}

/////////////////////////////////////// typeRefs ///////////////////////////////////////

func (*TypeRefs) Get

func (t *TypeRefs) Get(index int) reflect.Type

type UnknownException added in v1.6.1

type UnknownException struct {
	SerialVersionUID     int64
	DetailMessage        string
	SuppressedExceptions []java_exception.Throwabler
	StackTrace           []java_exception.StackTraceElement
	Cause                java_exception.Throwabler
	// contains filtered or unexported fields
}

func (UnknownException) Error added in v1.6.1

func (e UnknownException) Error() string

Error output error message

func (UnknownException) GetStackTrace added in v1.6.1

equals to getStackTrace in java

func (UnknownException) JavaClassName added in v1.6.1

func (e UnknownException) JavaClassName() string

JavaClassName java fully qualified path

Directories

Path Synopsis
* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements.
* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements.
testcases
tools
gen-go-enum command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL