Search code examples
javaandroidarchitecturefriend

Friend Package Pattern problems


I came accross the friend package pattern described here: http://wiki.apidesign.org/wiki/APIDesignPatterns:FriendPackages

I simply implemented the example but it does not work for me. I always get the error

IllegalStateException: Something is wrong: null

The error is thrown in the Accessor class.

The example tells that creating a new object is done by calling

Item item = Accessor.getDefault().newItem();

But neither Accessor.setDefault(Accessor) will be called nor the static initialization block will be called.

static {
    Accessor.setDefault(new AccessorImpl());
}

How should this work?


Solution

  • Finally it works. If you open the class files in the example you see that the Accessor class contains code that is not mentioned in the example. If you insert this code, it works.

    private static final Class<?> INIT_API_CLASS = loadClass(
            Item.class.getName()
    );
    
    private static Class<?> loadClass(String name) {
        try {
            return Class.forName(name, true, Accessor.class.getClassLoader()
            );
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }