Final Fields Specifics

Db4o uses reflection to store and retrieve objects from the database file. In the case of final fields db4o needs a successful call to java.lang.Field#setAccessible to allow write access to those fields. Unfortunately different Java versions produce different results in this case. To be more specific:

You can use the following example code to check final fields behavior with different java versions:

TestFinal.java
/**//* Copyright (C) 2007 Versant Inc. http://www.db4o.com */
package com.db4odoc.finalfields;
import java.io.File;

import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;

public class TestFinal
 {
  private static final String DB4O_FILE_NAME = "reference.db4o";
  // non-final fields
  public int    _i;
  public String _s;
   // final fields storing the same values as above
  public final  int    _final_i;
  public final String _final_s;
  
   public static void main(String[] args)
    {
      new File(DB4O_FILE_NAME).delete();
      ObjectContainer container = Db4o.openFile(DB4O_FILE_NAME);
      try  {
        TestFinal test = new TestFinal(1,"test");
        container.store(test);
        System.out.println("Added: " + test);
      } finally  {
        // Close does implicit commit and refreshes the reference cache
        container.close();
      }
      container = Db4o.openFile(DB4O_FILE_NAME);
      try  {
        ObjectSet result = container.queryByExample(null);
        listResult(result);
      } finally  { 
        container.close();
      }
   }
   // end main
   
   public TestFinal(int i, String s)
    {
     // initialize final and non-final fields with the same values
      _i       = i;
      _s       = s;
      _final_i = i;
      _final_s = s;
   }
   // end TestFinal

   public String toString()
    {
      return "Int - " + _i + "; String - " + _s + "; FINAL Int - " 
+ _final_i + "; FINAL String - " + _final_s;
   }
   // end toString
   
   private static void listResult(ObjectSet result)
    {
      while(result.hasNext())  {
         System.out.println(result.next());
     }
   }
   // end listResult
}

If you are using Eclipse it is easy to switch between java versions - you can switch to the versions lower than the one installed on your computer without having to install them all. For example if you are using JDK6 you can easily test your project on JDK1.1 - 1.4 and JDK5. Just go to the project properties, select "Java Build Path" on the left panel and "Libraries" tab on the right panel. Remove the system library currently used. Select "Add library->JRE System Library"; on the next screen check the "Execution Environment" radio button and select the desired environment from the list.

Don't forget to use the appropriate db4o version for the selected java environment version. See db4o on Java Platformsfor more information.

Download example code: