View RSS Feed

Hibernate

Unusual members, part 1

Rate this Entry
by , 08-12-2011 at 01:09 AM (915 Views)
Did you ever want to run something the first, and only first, time a class was being used.
Perhaps wanted to do some complex calculations and assign it to a constant.

One way to do this is by writing, for example:
Java Code:
public class YourClass
{
    public static final int YOUR_CONSTANT = constantValue();

    private static int constantValue()
    {
        int value1 = 0, value2 = 1;
        int value = 0;
        for (int i = 0; i < 10; i++)
        {
            value = value1 + value2;
            value2 = value1;
            value1 = value;
        }
        return value:
    }
}
All static variables are assigned direct when the class is first being used,
so if you want to print "Hello", you could do so in a method used by a dummy variable.

Java Code:
public class YourClass
{
    private static final Void IM_A_DUMMY = printHello();

    private static Void printHello()
    {
        System.out.println("Hello");
        return null;
    }
}
But there is a much prettier way to do this, especially for more complex code: by using a class initialiser:

Java Code:
public class MyClass
{
    private static final Void DUMMY = dummysCode();
    public static final int VALUE;

    /**
     * Class initialiser
     */
    static
    {
        System.out.println("Hello");
        VALUE = 10;
    }

    private static final Void ANOTHER_DUMMY = anotherDummysCode();

    static
    {
        System.out.println("Initialised!");
    }



    private static Void dummysCode()
    {
        System.out.println("Dummy's code");
        return null;
    }

    private static Void anotherDummysCode()
    {
        System.out.println("Another dummy's code");
        return null;
    }



    public static void main(final String... arg)
    {
        System.out.println(VALUE);
    }

}
Running main() will print:
Dummy's code
Hello
Another dummy's code
Initialised!
10

Variable as assigned from the top down, running any class initialiser in the way.

Submit "Unusual members, part 1" to Facebook Submit "Unusual members, part 1" to Digg Submit "Unusual members, part 1" to del.icio.us Submit "Unusual members, part 1" to StumbleUpon Submit "Unusual members, part 1" to Google

Updated 08-12-2011 at 06:45 AM by Hibernate

Tags: None Add / Edit Tags
Categories
Java's syntax

Comments