Freitag, 30. November 2012

Abolishing Java's final restriction

The keyword final can be use to indicate, that a variable should not be changed after it has been assign. It is a constant value. Java requires the assignment to be taken place in the initialization of a object. This means that a final can be initialized in the constructor or a instance initialization block. But it can not be initialized in a method. If this functionality is required it has to be coded by hand. The following code emulates final with the ability to set the value out of the initialization scope of an object.
// -*- compile-command: "javac fin.java && java fin"; -*-

class fin
{
    private class Final<Type>
    {
        private Type value;
        private boolean defined = false;

        public void set (Type value)
        {
            if (defined)
                throw new IllegalStateException ("Value is already defiend.");
            this.value = value;
            defined = true;
        }

        Type get ()
        {
            if (!defined)
                throw new IllegalStateException ("Value is undefiend.");
            return value;
        }

        boolean defined ()
        {
            return defined;
        }
    }

    void run()
    {
        Final<Integer> i = new Final<Integer>();

        i.set(42);                    // ok
        System.out.println (i.get()); // ok
        i.set(43);                    // failure
    }

    public static void main (String argv[])
    {
        new fin().run();
    }
}

Keine Kommentare: