### Custom writeObject Transformer (V2) Source: https://context7.com/tcalmant/python-javaobj/llms.txt Handles Java classes with custom writeObject() methods by implementing load_custom_writeObject in a transformer. This example specifically handles java.util.Random. ```python import javaobj.v2 as javaobj from javaobj.v2.api import ObjectTransformer from javaobj.v2.beans import JavaInstance, JavaClassDesc, JavaField, FieldType class RandomChildInstance(JavaInstance): def load_from_instance(self, indent=0): """Process parsed field data""" if self.classdesc and self.classdesc in self.field_data: fields = self.classdesc.fields_names values = [ self.field_data[self.classdesc][self.classdesc.fields[i]] for i in range(len(fields)) ] self.field_data = dict(zip(fields, values)) return True return False class JavaRandomTransformer(ObjectTransformer): def __init__(self): self.name = "java.util.Random" self.field_names = ["haveNextNextGaussian", "nextNextGaussian", "seed"] self.field_types = [FieldType.BOOLEAN, FieldType.DOUBLE, FieldType.LONG] def load_custom_writeObject(self, parser, reader, name): """Handle custom writeObject serialization for java.util.Random""" if name != self.name: return None # Read the custom-written fields fields = [] values = [] for f_name, f_type in zip(self.field_names, self.field_types): values.append(parser._read_field_value(f_type)) fields.append(JavaField(f_type, f_name)) # Create a class description with the parsed data class_desc = JavaClassDesc(javaobj.beans.ClassDescType.NORMALCLASS) class_desc.name = self.name class_desc.fields = fields class_desc.field_data = values return class_desc # Use multiple transformers together transformers = [ JavaRandomTransformer(), # DefaultObjectTransformer is added automatically if not present ] with open("random_object.ser", "rb") as fd: obj = javaobj.load(fd, *transformers) ``` -------------------------------- ### load(fd, *transformers, use_numpy_arrays=False) Source: https://github.com/tcalmant/python-javaobj/blob/master/README.md Parses the content of a file descriptor opened in binary mode. ```APIDOC ## load(fd, *transformers, use_numpy_arrays=False) ### Description Parses the content of the given file descriptor, opened in binary mode (rb). The method accepts a list of custom object transformers. ### Parameters - **fd** (file descriptor) - Required - File descriptor opened in binary mode. - **transformers** (list) - Optional - List of custom object transformers. - **use_numpy_arrays** (bool) - Optional - If True, arrays of primitive type elements are loaded using numpy if available. ``` -------------------------------- ### loads(bytes, *transformers, use_numpy_arrays=False) Source: https://github.com/tcalmant/python-javaobj/blob/master/README.md Parses binary data provided as bytes. ```APIDOC ## loads(bytes, *transformers, use_numpy_arrays=False) ### Description A shortcut to the load() method, providing it the binary data using a BytesIO object. ### Parameters - **bytes** (bytes) - Required - Binary data to parse. - **transformers** (list) - Optional - List of custom object transformers. - **use_numpy_arrays** (bool) - Optional - If True, arrays of primitive type elements are loaded using numpy if available. ``` -------------------------------- ### Load and Inspect Java Arrays in Python Source: https://context7.com/tcalmant/python-javaobj/llms.txt Demonstrates loading Java serialized arrays and accessing their elements like Python lists. Supports numpy integration for primitive arrays for performance. ```python import javaobj # Load arrays with open("objArrays.ser", "rb") as fd: obj = javaobj.load(fd) # JavaArray behaves like a Python list int_array = obj.intArrayField print(f"Int array: {list(int_array)}") print(f"First element: {int_array[0]}") print(f"Length: {len(int_array)}") # JavaByteArray for byte arrays byte_array = obj.byteArrayField print(f"Byte array: {bytes(byte_array)}") # Iterate over array elements for element in int_array: print(element) # With numpy arrays for better performance with open("large_array.ser", "rb") as fd: marshaller = javaobj.JavaObjectUnmarshaller(fd, use_numpy_arrays=True) obj = marshaller.readObject() # Arrays of primitives are now numpy arrays numpy_array = obj.largeIntArray print(f"Mean: {numpy_array.mean()}, Sum: {numpy_array.sum()}") ``` -------------------------------- ### Handle Java 8+ Time Classes in Python Source: https://context7.com/tcalmant/python-javaobj/llms.txt Illustrates how to use the JavaTime transformer to parse and access components of Java 8+ time classes like Instant, LocalDate, and ZonedDateTime. ```python import javaobj with open("testTime.ser", "rb") as fd: marshaller = javaobj.JavaObjectUnmarshaller(fd) marshaller.add_transformer(javaobj.DefaultObjectTransformer()) time_obj = marshaller.readObject() # JavaTime contains parsed time components print(f"Type: {time_obj.type}") print(f"Year: {time_obj.year}") print(f"Month: {time_obj.month}") print(f"Day: {time_obj.day}") print(f"Hour: {time_obj.hour}") print(f"Minute: {time_obj.minute}") print(f"Second: {time_obj.second}") print(f"Nano: {time_obj.nano}") print(f"Offset: {time_obj.offset}") print(f"Zone: {time_obj.zone}") # Supported java.time types: # - Duration (DURATION_TYPE = 1) # - Instant (INSTANT_TYPE = 2) # - LocalDate (LOCAL_DATE_TYPE = 3) # - LocalTime (LOCAL_TIME_TYPE = 4) # - LocalDateTime (LOCAL_DATE_TIME_TYPE = 5) # - ZonedDateTime (ZONE_DATE_TIME_TYPE = 6) # - ZoneRegion (ZONE_REGION_TYPE = 7) # - ZoneOffset (ZONE_OFFSET_TYPE = 8) # - OffsetTime (OFFSET_TIME_TYPE = 9) # - OffsetDateTime (OFFSET_DATE_TIME_TYPE = 10) # - Year (YEAR_TYPE = 11) # - YearMonth (YEAR_MONTH_TYPE = 12) # - MonthDay (MONTH_DAY_TYPE = 13) # - Period (PERIOD_TYPE = 14) ``` -------------------------------- ### Serialize Java Objects to File Source: https://github.com/tcalmant/python-javaobj/blob/master/README.md Standard procedure for writing serialized Java objects to a file using ObjectOutputStream. ```java ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("custom_objects.ser")); CustomClass writer = new CustomClass(); writer.start(oos); oos.flush(); oos.close(); ``` -------------------------------- ### Load Java Objects with V2 Parser Source: https://context7.com/tcalmant/python-javaobj/llms.txt The V2 parser offers enhanced parsing capabilities for complex structures. Note that this implementation is read-only. ```python import javaobj.v2 as javaobj # Load from file descriptor with open("complex_object.ser", "rb") as fd: pobj = javaobj.load(fd) # Use dump() method to inspect the parsed structure print(pobj.dump()) ``` -------------------------------- ### Define Custom JavaInstance for HashMap Source: https://github.com/tcalmant/python-javaobj/blob/master/README.md Create a Python class that inherits from `dict` and `javaobj.v2.beans.JavaInstance` to represent Java HashMaps. Implement `load_from_blockdata` and `load_from_instance` to handle custom parsing logic, especially for data stored in annotations. ```python class JavaMap(dict, javaobj.v2.beans.JavaInstance): """ Inherits from dict for Python usage, JavaInstance for parsing purpose """ def __init__(self): # Don't forget to call both constructors dict.__init__(self) JavaInstance.__init__(self) def load_from_blockdata(self, parser, reader, indent=0): """ Reads content stored in a block data. This method is called only if the class description has both the `SC_EXTERNALIZABLE` and `SC_BLOCK_DATA` flags set. The stream parsing will stop and fail if this method returns False. :param parser: The JavaStreamParser in use :param reader: The underlying data stream reader :param indent: Indentation to use in logs :return: True on success, False on error """ # This kind of class is not supposed to have the SC_BLOCK_DATA flag set return False def load_from_instance(self, indent=0): # type: (int) -> bool """ Load content from the parsed instance object. This method is called after the block data (if any), the fields and the annotations have been loaded. :param indent: Indentation to use while logging :return: True on success (currently ignored) """ # Maps have their content in their annotations for cd, annotations in self.annotations.items(): # Annotations are associated to their definition class if cd.name == "java.util.HashMap": # We are in the annotation created by the handled class # Group annotation elements 2 by 2 # (storage is: key, value, key, value, ...) args = [iter(annotations[1:])] * 2 for key, value in zip(*args): self[key] = value # Job done return True # Couldn't load the data return False ``` -------------------------------- ### Load Java Object from File (V1) Source: https://context7.com/tcalmant/python-javaobj/llms.txt Use load() to deserialize Java objects from binary files. This function automatically detects and decompresses GZipped serialization files. ```python import javaobj # Load a serialized Java object from file with open("serialized_object.ser", "rb") as fd: obj = javaobj.load(fd) # Access object attributes (field names from Java class) print(obj.classdesc.name) # Print the Java class name print(obj.value) # Access a field named 'value' print(obj.next) # Access a field named 'next' # Handle GZipped files automatically with open("compressed_object.ser.gz", "rb") as fd: obj = javaobj.load(fd) # Automatically decompresses ``` -------------------------------- ### Inspect Java Class Information in Python Source: https://context7.com/tcalmant/python-javaobj/llms.txt Demonstrates how to retrieve and display metadata about a Java class from a serialized object, including its name, serial UID, fields, and superclass hierarchy. ```python import javaobj with open("testClass.ser", "rb") as fd: obj = javaobj.load(fd) # Get class description classdesc = obj.get_class() # or obj.classdesc # Class metadata print(f"Class name: {classdesc.name}") print(f"Serial UID: {classdesc.serialVersionUID}") print(f"Flags: 0x{classdesc.flags:02X}") # Field information print("Fields:") for name, type_str in zip(classdesc.fields_names, classdesc.fields_types): print(f" {type_str} {name}") # Superclass hierarchy superclass = classdesc.superclass while superclass: print(f"Superclass: {superclass.name}") superclass = superclass.superclass # Annotations (for objects with custom writeObject) if obj.annotations: print(f"Annotations: {obj.annotations}") ``` -------------------------------- ### Automatic Java Collection Conversion Source: https://context7.com/tcalmant/python-javaobj/llms.txt Demonstrates automatic conversion of common Java collection types to their Python equivalents using DefaultObjectTransformer. Includes HashMap, ArrayList, HashSet, and TreeSet. ```python import javaobj # Automatic collection conversion with open("objCollections.ser", "rb") as fd: marshaller = javaobj.JavaObjectUnmarshaller(fd) marshaller.add_transformer(javaobj.DefaultObjectTransformer()) obj = marshaller.readObject() # Java HashMap -> Python dict hash_map = obj.mapField print(f"HashMap: {dict(hash_map)}") # Java ArrayList -> Python list array_list = obj.listField print(f"ArrayList: {list(array_list)}") # Java HashSet -> Python set hash_set = obj.setField print(f"HashSet: {set(hash_set)}") # Java TreeSet -> Python set (sorted in Java, unordered in Python) tree_set = obj.treeSetField print(f"TreeSet: {set(tree_set)}") # Supported automatic conversions: # java.util.ArrayList -> list # java.util.LinkedList -> list # java.util.HashMap -> dict # java.util.LinkedHashMap -> dict # java.util.TreeMap -> dict # java.util.HashSet -> set ``` -------------------------------- ### Load Java Object from File Source: https://github.com/tcalmant/python-javaobj/blob/master/README.md Use `javaobj.v2.load` to parse a Java serialized object from a file descriptor opened in binary mode. Custom transformers can be provided to customize object loading. The `use_numpy_arrays` flag enables NumPy for primitive arrays. ```python import javaobj.v2 as javaobj with open("obj5.ser", "rb") as fd: pobj = javaobj.load(fd) print(pobj.dump()) ``` -------------------------------- ### Implement Custom Object Transformer Source: https://github.com/tcalmant/python-javaobj/blob/master/README.md Create a custom object transformer by inheriting from `javaobj.v2.api.ObjectTransformer`. Implement the `create_instance` method to return a custom `JavaInstance` for specific Java class names, enabling custom deserialization logic. ```python class MapObjectTransformer(javaobj.v2.api.ObjectTransformer): """ Creates a JavaInstance object with custom loading methods for the classes it can handle """ def create_instance(self, classdesc): # type: (JavaClassDesc) -> Optional[JavaInstance] """ Transforms a parsed Java object into a Python object :param classdesc: The description of a Java class :return: The Python form of the object, or the original JavaObject """ if classdesc.name == "java.util.HashMap": # We can handle this class description return JavaMap() else: # Return None if the class is not handled return None ``` -------------------------------- ### Implement Custom Transformers for Specific Java Classes Source: https://github.com/tcalmant/python-javaobj/blob/master/README.md Create specific transformer classes by inheriting from `BaseTransformer` and providing a mapping of Java class names to their corresponding Python instance representations. This allows `javaobj` to instantiate the correct Python objects when deserializing. ```python class RandomChildTransformer(BaseTransformer): def __init__(self): super(RandomChildTransformer, self).__init__( {"RandomChild": RandomChildInstance} ) class CustomWriterTransformer(BaseTransformer): def __init__(self): super(CustomWriterTransformer, self).__init__( {"CustomWriter": CustomWriterInstance} ) ``` -------------------------------- ### Load Java Object from Bytes Source: https://context7.com/tcalmant/python-javaobj/llms.txt Loads a Java object serialized into bytes from a file. Supports enabling numpy arrays for primitive type arrays. ```python import javaobj # Load from bytes with open("obj5.ser", "rb") as fd: data = fd.read() pobj = javaobj.loads(data) print(pobj) # Enable numpy arrays for primitive type arrays with open("large_arrays.ser", "rb") as fd: pobj = javaobj.load(fd, use_numpy_arrays=True) ``` -------------------------------- ### Serialize Java Objects (V1 - dumps) Source: https://context7.com/tcalmant/python-javaobj/llms.txt Use dumps() to convert Python objects back into the Java serialization format for round-trip operations. ```python import javaobj # First load an existing Java object with open("original.ser", "rb") as fd: obj = javaobj.load(fd) # Modify the object obj.value = 42 obj.message = "Updated" # Serialize back to bytes serialized = javaobj.dumps(obj) # Write to a new file with open("modified.ser", "wb") as fd: fd.write(serialized) ``` -------------------------------- ### Define Base Transformer for Custom Java Object Loading Source: https://github.com/tcalmant/python-javaobj/blob/master/README.md Inherit from `javaobj.v2.transformers.ObjectTransformer` to create custom loading logic for specific Java classes. The `create_instance` method determines if the transformer can handle a given `classdesc` and returns a Python instance if it can. ```python class BaseTransformer(javaobj.v2.transformers.ObjectTransformer): """ Creates a JavaInstance object with custom loading methods for the classes it can handle """ def __init__(self, handled_classes=None): self.instance = None self.handled_classes = handled_classes or {} def create_instance(self, classdesc): """ Transforms a parsed Java object into a Python object :param classdesc: The description of a Java class :return: The Python form of the object, or the original JavaObject """ if classdesc.name in self.handled_classes: self.instance = self.handled_classes[classdesc.name]() return self.instance return None ``` -------------------------------- ### Load and Inspect Java Enums in Python Source: https://context7.com/tcalmant/python-javaobj/llms.txt Shows how to load Java serialized objects containing enum fields and access their class name and constant value. Includes a check for JavaEnum type. ```python import javaobj # Load an object containing enum fields with open("objEnums.ser", "rb") as fd: obj = javaobj.load(fd) # Access enum value enum_field = obj.statusField print(f"Enum class: {enum_field.classdesc.name}") print(f"Enum constant: {enum_field.constant}") # Check enum type if isinstance(enum_field, javaobj.JavaEnum): print(f"This is a Java enum: {enum_field.constant}") # Serialize back (V1 only) serialized = javaobj.dumps(obj) ``` -------------------------------- ### Use JavaObjectUnmarshaller Class (V1) Source: https://context7.com/tcalmant/python-javaobj/llms.txt The JavaObjectUnmarshaller class allows for granular control over stream reading and custom object transformation. Enable use_numpy_arrays for improved performance with large data structures. ```python import javaobj with open("objCollections.ser", "rb") as fd: # Create unmarshaller with the file stream marshaller = javaobj.JavaObjectUnmarshaller(fd) # Add custom transformer (optional) marshaller.add_transformer(javaobj.DefaultObjectTransformer()) # Read first object obj1 = marshaller.readObject() print(f"Object 1: value={obj1.value}, next={obj1.next}") # Read second object from same stream obj2 = marshaller.readObject() print(f"Object 2: {obj2}") # Use numpy arrays for better performance with large arrays with open("large_arrays.ser", "rb") as fd: marshaller = javaobj.JavaObjectUnmarshaller(fd, use_numpy_arrays=True) array_obj = marshaller.readObject() ``` -------------------------------- ### Custom HashMap Transformer (V2) Source: https://context7.com/tcalmant/python-javaobj/llms.txt Implements a custom transformer to handle java.util.HashMap serialization. Inherits from ObjectTransformer and implements create_instance to return a custom JavaInstance subclass. ```python import javaobj.v2 as javaobj from javaobj.v2.api import ObjectTransformer from javaobj.v2.beans import JavaInstance # Define a custom instance class class CustomHashMapInstance(dict, JavaInstance): def __init__(self): dict.__init__(self) JavaInstance.__init__(self) def load_from_instance(self, indent=0): """Called after fields and annotations are parsed""" for cd, annotations in self.annotations.items(): if cd.name == "java.util.HashMap": # Annotations contain: [size, key1, val1, key2, val2, ...] args = [iter(annotations[1:])] * 2 for key, value in zip(*args): self[key] = value return True return False # Define the transformer class CustomMapTransformer(ObjectTransformer): def create_instance(self, classdesc): """Create instance for classes we handle""" if classdesc.name == "java.util.HashMap": return CustomHashMapInstance() return None # Return None for unhandled classes # Use the custom transformer with open("hashmap.ser", "rb") as fd: result = javaobj.load(fd, CustomMapTransformer()) print(f"Loaded HashMap with {len(result)} entries") for key, value in result.items(): print(f" {key}: {value}") ``` -------------------------------- ### V2 Parser Dump and Debug in Python Source: https://context7.com/tcalmant/python-javaobj/llms.txt Utilizes the V2 parser's `dump()` method to generate a formatted string representation of complex Java object structures, aiding in debugging. ```python import javaobj.v2 as javaobj with open("complex_object.ser", "rb") as fd: obj = javaobj.load(fd) # Generate formatted dump of object structure dump_output = obj.dump() print(dump_output) # Example output: # [instance 0x7e0002: 7e0001 / com.example.MyClass] # com.example.MyClass -- 2 fields # INTEGER count: 42 # OBJECT name: # [String 0x7e0003: 'test'] # [/instance 0x7e0002] # For arrays array_obj = obj.myArray print(array_obj.dump()) # [array 0x7e0004: 3 items - stored as list] # 'item1', # 'item2', # 'item3', # [/array 0x7e0004] ``` -------------------------------- ### Define Python Representation for CustomWriter Java Instance Source: https://github.com/tcalmant/python-javaobj/blob/master/README.md Inherit from `javaobj.v2.beans.JavaInstance` to define how a `CustomWriter` Java object is represented and loaded in Python. The `load_from_instance` method customizes the parsing of raw data and annotations to populate the instance's fields. ```python class CustomWriterInstance(javaobj.v2.beans.JavaInstance): def __init__(self): javaobj.v2.beans.JavaInstance.__init__(self) def load_from_instance(self): """ Updates the content of this instance from its parsed fields and annotations :return: True on success, False on error """ if self.classdesc and self.classdesc in self.annotations: # Here, we known there is something written before the fields, # even if it's not declared in the class description fields = ["int_not_in_fields"] + self.classdesc.fields_names raw_data = self.annotations[self.classdesc] int_not_in_fields = struct.unpack( ">i", BytesIO(raw_data[0].data).read(4) )[0] custom_obj = raw_data[1] values = [int_not_in_fields, custom_obj] self.field_data = dict(zip(fields, values)) return True return False ``` -------------------------------- ### Load Java Object with Custom Transformers Source: https://github.com/tcalmant/python-javaobj/blob/master/README.md Use custom transformers to modify the deserialization process. This is useful for handling specific object structures or custom serialization logic. ```python transformers = [ CustomWriterTransformer(), RandomChildTransformer(), JavaRandomTransformer() ] pobj = javaobj.loads("custom_objects.ser", *transformers) ``` -------------------------------- ### Load Java Object from Bytes (V1) Source: https://context7.com/tcalmant/python-javaobj/llms.txt Use loads() to deserialize Java objects directly from a bytes string. The ignore_remaining_data parameter can be used to suppress warnings about trailing data. ```python import javaobj # Load from bytes with open("obj5.ser", "rb") as fd: serialized_bytes = fd.read() # Deserialize the bytes pobj = javaobj.loads(serialized_bytes) print(pobj) # Ignore trailing data warnings pobj = javaobj.loads(serialized_bytes, ignore_remaining_data=True) ``` -------------------------------- ### Define Transformer for java.util.Random with Custom Fields Source: https://github.com/tcalmant/python-javaobj/blob/master/README.md This transformer specifically handles `java.util.Random` objects. It defines the expected field names and types, and implements `load_custom_writeObject` to parse these fields according to Java serialization conventions. ```python class JavaRandomTransformer(BaseTransformer): def __init__(self): super(JavaRandomTransformer, self).__init__() self.name = "java.util.Random" self.field_names = ["haveNextNextGaussian", "nextNextGaussian", "seed"] self.field_types = [ javaobj.v2.beans.FieldType.BOOLEAN, javaobj.v2.beans.FieldType.DOUBLE, javaobj.v2.beans.FieldType.LONG, ] def load_custom_writeObject(self, parser, reader, name): if name != self.name: return None fields = [] values = [] for f_name, f_type in zip(self.field_names, self.field_types): values.append(parser._read_field_value(f_type)) fields.append(javaobj.beans.JavaField(f_type, f_name)) class_desc = javaobj.beans.JavaClassDesc( javaobj.beans.ClassDescType.NORMALCLASS ) class_desc.name = self.name class_desc.desc_flags = javaobj.beans.ClassDataType.EXTERNAL_CONTENTS class_desc.fields = fields class_desc.field_data = values return class_desc ``` -------------------------------- ### Use JavaObjectMarshaller Class (V1) Source: https://context7.com/tcalmant/python-javaobj/llms.txt The JavaObjectMarshaller class provides a structured way to serialize various Java types including arrays, enums, and strings. ```python import javaobj # Load an object to modify and re-serialize with open("original.ser", "rb") as fd: obj = javaobj.load(fd) # Create a marshaller marshaller = javaobj.JavaObjectMarshaller() # Serialize the object serialized_data = marshaller.dump(obj) # The marshaller handles various types: # - JavaObject instances # - JavaArray and JavaByteArray # - JavaEnum values # - JavaString objects # - JavaClass descriptions # - None (null) values # - Block data (raw strings) print(f"Serialized {len(serialized_data)} bytes") ``` -------------------------------- ### Define Python Representation for RandomChild Java Instance Source: https://github.com/tcalmant/python-javaobj/blob/master/README.md Inherit from `javaobj.v2.beans.JavaInstance` to define how a `RandomChild` Java object is represented in Python. The `load_from_instance` method handles parsing fields and annotations, including those from superclasses, to populate the instance's `field_data`. ```python class RandomChildInstance(javaobj.v2.beans.JavaInstance): def load_from_instance(self): """ Updates the content of this instance from its parsed fields and annotations :return: True on success, False on error """ if self.classdesc and self.classdesc in self.field_data: fields = self.classdesc.fields_names values = [ self.field_data[self.classdesc][self.classdesc.fields[i]] for i in range(len(fields)) ] self.field_data = dict(zip(fields, values)) if ( self.classdesc.super_class and self.classdesc.super_class in self.annotations ): super_class = self.annotations[self.classdesc.super_class][0] self.annotations = dict( zip(super_class.fields_names, super_class.field_data) ) return True return False ``` -------------------------------- ### Define Serializable Java Classes Source: https://github.com/tcalmant/python-javaobj/blob/master/README.md Classes implementing Serializable with custom writeObject methods to control the serialization process. ```java class CustomClass implements Serializable { private static final long serialVersionUID = 1; public void start(ObjectOutputStream out) throws Exception { this.writeObject(out); } private void writeObject(ObjectOutputStream out) throws IOException { CustomWriter custom = new CustomWriter(42); out.writeObject(custom); out.flush(); } } class RandomChild extends Random { private static final long serialVersionUID = 1; private int num = 1; private double doub = 4.5; RandomChild(int seed) { super(seed); } } class CustomWriter implements Serializable { protected RandomChild custom_obj; CustomWriter(int seed) { custom_obj = new RandomChild(seed); } private static final long serialVersionUID = 1; private static final int CURRENT_SERIAL_VERSION = 0; private void writeObject(ObjectOutputStream out) throws IOException { out.writeInt(CURRENT_SERIAL_VERSION); out.writeObject(custom_obj); } } ``` -------------------------------- ### Unmarshall Java Serialized Object (V1) Source: https://github.com/tcalmant/python-javaobj/blob/master/README.md Reads a Java serialized object from a file and unmarshals it into a Python object using the v1 parser. Ensure the file is opened in binary read mode. ```python import javaobj with open("obj5.ser", "rb") as fd: jobj = fd.read() pobj = javaobj.loads(jobj) print(pobj) ``` -------------------------------- ### Unmarshall Java Serialized Object Directly (V1) Source: https://github.com/tcalmant/python-javaobj/blob/master/README.md Uses JavaObjectUnmarshaller to read Java objects directly from a file descriptor. This method is useful for processing multiple objects from a single stream. It's recommended to explicitly import from javaobj.v1 for new code. ```python import javaobj with open("objCollections.ser", "rb") as fd: marshaller = javaobj.JavaObjectUnmarshaller(fd) pobj = marshaller.readObject() print(pobj.value, "should be", 17) print(pobj.next, "should be", True) pobj = marshaller.readObject() ``` -------------------------------- ### Access Non-Serialized Static Field Source: https://github.com/tcalmant/python-javaobj/blob/master/README.md Access fields that are not serialized by default, such as static fields. These fields can be accessed through the 'field_data' attribute of the loaded object. ```python print(pobj.field_data["int_not_in_fields"]) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.