will
will

Reputation: 10650

Java run code when class is imported

I know there is a question on here somewhere answering this, as I've read it before. I just can't for the life of me find it, nor find it on google.

The question i remember from before was about the order of various methods and pieces of code being called, and there was a particular section which was apparently called the second the class is imported (which can also be used to do nasty unexpected things). What is this called / how would i go about doing it?

If i recall correctly, it was something like this:

Java file 1:

...
import somepackage.myclass; //prints "class imported"
...
myclass a = new myclass(); //print "constructor"
...

Java file 2

package somepackage;

public class myclass {
    ...
    //Something to print out "class imported"
    ...
    public void myclass(){
      System.out.println("constructor");
    }
}

The question / answers had several such constructs like this, but i can't remember what any of them were called. Can someone point me in the right direction please?

Upvotes: 3

Views: 1476

Answers (2)

Mshnik
Mshnik

Reputation: 7032

You're probably thinking of a static initializer:

package somepackage;

public class myclass {
    static{
      System.out.println("class imported");
    }

    public void myclass(){
      System.out.println("constructor");
    }
}

The static initializer for a class gets run when the class is first accessed, either to create an instance, or to access a static method or field.

Upvotes: 2

mk.
mk.

Reputation: 11710

Try this:

public class Myclass {
    static {
        System.out.println("test");
    }
}

This is called a Static Initialization Block.

Upvotes: 4

Related Questions