You are here: Implementation Strategies > TypeHandlers


One of the most important and convenient things that db4o provides is the ability to store any object just as it is: no interfaces to be implemented, no custom fields, no attributes/annotations - nothing, just a plain object. However, it is not as simple as it may seem - objects are getting more and more complex and sometimes the generic solution is not good enough for specific objects.

This problem was recognized by db4o team long ago, and various solutions were provided to customize the way an object is stored: configuration readAs method, Translators, transient fields in Java and .NET and classes, custom marshallers etc. However all these means were rather fixing the symptoms but not the disease itself. And the fact is that there is no single generic way to store just any available or future object in the best possible way. But luckily we don't even need it - all we need is a simple way to write a specific persistence solution for any custom object, and now db4o provides this way though a pluggable TypeHandler4/ITypeHandler4 interface:


configuration.common().registerTypeHandler(TypeHandlerPredicate, TypeHandler4);

In the method above TypeHandler4 interface provides methods that define how an object is converted to a low-level byte-array and back and how it behaves in a query:
/**//* Copyright (C) 2004 - 2007  Versant Inc. */

package com.db4o.internal;

import com.db4o.ext.*;
import com.db4o.internal.fieldhandlers.*;
import com.db4o.marshall.*;

/** *//**
 * @exclude
public interface TypeHandler4 extends Comparable4, FieldHandler  {
  void delete(DeleteContext context) throws Db4oIOException;
  void defragment(DefragmentContext context);

  Object read(ReadContext context);
    void write(WriteContext context, Object obj);
/**//* Copyright (C) 2004   Versant Inc. */

package com.db4o.internal;


/** *//**
 * @exclude
public interface Comparable4  {
  PreparedComparison prepareComparison(Object obj);

TypeHandlerPredicate provides a #match method, which returns true for objects that should be handled with the specified TypeHandler.

Type handler functionality is best explained on a working example.

Usecases and other benefits of the pluggable typehandler interface are reviewed here.

Download example code: