It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
What is the best and cleanest way to do this? Specifically, I need some code in a static initializer block to run in that class, but I'd like to make this as clean-looking as possible.
Loading != Initialization.
You want your class to be initialized (this is when static blocks executed, among other things).
An excerpt from the Java Language Specification says:
A class or interface type T will be initialized immediately before the first occurrence of >any one of the following:
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant variable (§4.12.4).
T is a top-level class, and an assert statement (§14.10) lexically nested within T is executed.
Invocation of certain reflective methods in class Class and in package java.lang.reflect also causes class or interface initialization. A class or interface will not be initialized under any other circumstance.
Doh, anovstrup, already said it: Just make an empty static function called init. Be sure to document that well... I personally can't see any use case for this in the context of well formed code though.
You can use the following code to force initialization of a class:
//... Foo.class ... //OLD CODE
... forceInit(Foo.class) ... //NEW CODE
/**
* Forces the initialization of the class pertaining to
* the specified <tt>Class</tt> object.
* This method does nothing if the class is already
* initialized prior to invocation.
*
* #param klass the class for which to force initialization
* #return <tt>klass</tt>
*/
public static <T> Class<T> forceInit(Class<T> klass) {
try {
Class.forName(klass.getName(), true, klass.getClassLoader());
} catch (ClassNotFoundException e) {
throw new AssertionError(e); // Can't happen
}
return klass;
}
try
{
Class.forName(class name as string)
}
catch(ClassNotFoundException e)
{
whatever
}
That should do it.
#Longpoke
Maybe I am misunderstanding something then. Can you create an example where a class is loaded but the static initializer is not executed? Here is an example that does nothing but print out that it has loaded:
package test;
public class TestStatic
{
public static void main(String[] args)
{
try
{
Class.forName("test.Static");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
With the following Static class being loaded:
package test;
public class Static
{
static
{
System.out.println("Static Initializer ran...");
}
}
If the static initializers are not ran until the conditions you listed are met then why does this println get executed when I run my test? That is which of your listed conditions am I meeting?
Invisible dependencies between classes is not a good idea. I suggest moving the code in static initializer block to a static method and calling it directly in the dependent class. The static initializer block can be rewritten to call the newly created static method.
If you need to statically initilize something in a Class that means there must be client classes dependent on that.
If there is one client, or let's call it a natural home for the initializing block, I think it would be cleanest to initialize it there.
For the many equal clients case, it may be a good idea to verify from these classes that the static initalization in the other class was successful. Then the coupling is documented and you are sure the class is always initialized before the first client needs it.
One solution would be to call a static method:
public class A {
static { DebugUtils.FLAG_TEST_USER = true; }
static void init() {}
}
Then invoke A.init() to force initialization.
However, doing this at all is a code smell. Consider replacing your static code with a standard constructor in a singleton object.
Related
If seen this question here:
Instance initializer and *this* keyword
and now I ask myself is something like this:
public class Main {
public static void main(String args[]) {
new Main();
}
{ System.out.println(x); } //Error here
int x=1;
}
of any (even just theoritical) use? I mean this part:
{ System.out.println(x); } //Error here
As far as I can say its anonymous so I'd have no idea how to execute it manually, it doesn't seem to be executed automatically is not part of any function or whatsoever. Sorry if this questions is already answered, but the ones that I found targeted {} to restrict the variable scope but in this case I could not think of a way to get into that scope or make it run.
It's an instance initialization block. Whenever you create an instance of the class, it is executed before the body of the constructor you use.
Therefore the only way to execute it manually is by creating an instance of the class in which this block appears (or a sub-class of that class).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I was wondering whether it is possible to call a static method from a static block in order to initialize static variables. Is e.g. the following possible:
public class AppProperties {
private static final Logger logger = LoggerFactory.getLogger(AppProperties.class);
private static final String PARSER_PROPERTIES_FILE = "/parser.properties";
private static final Properties PARSER_PROPERTIES = new Properties();
private static final Properties DAO_PROPERTIES = new Properties();
static {
loadParserProperties();
loadDaoProperties();
// Some other configuration
}
public static void loadParserProperties() {
// Loading parser properties
}
// Further methods omitted
}
Is it good practice?
EDIT:
Oracle recommends initialization as follows:
class Whatever {
public static VarType myVar = initializeClassVariable();
private static VarType initializeClassVariable() {
// Initialization code goes here
}
}
Their explanation is:
The advantage of private static methods is that they can be reused
later if you need to reinitialize the class variable.
However, the AppProperties code is also reusable. I have a feeling that I am missing something. Calling static methods from static blocks isn't mentioned, that's why I assume it is bad practice.
Static block call your method only once at time of class creation, If you want to call method at time of class creation you can call it.
Static block is only way by which you can call your static methods at time of class creation.
This should not be any issue related to design or best practice.
Anyways, it is advisable to divide chunk of code/functionality into different functions, and making them static and calling from static block is something your applications demands during loading of class by JVM.
The advantage of static methods is that they can be reused later if you need . So, you kind of get more flexibility with a static method in comparison to the corresponding static initialization block.
for more info here
Calling to static method from static block it acceptable in the case of you really want to execute the content in the referred static method only one time when the class is getting initialize in the JVM first time. Further you have to keep it in mind this static block won't ever execute again even though you created multiple object in same type with in your application except the first creation.
However you have to use static variables to store if there any values need to be use with the other object creation cycles.
Some extra points about static block might help someone.
Calling static methods inside of static block is accepted only in below conditions.
1) It must contain main method if the java version is 7 or above. Else it will throw below error
Error: Main method not found in class MyClass, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
2) If java version is 6 or below, it will work fine even if we don't have main method.
Example :
// The below code would not work in JDK 1.7 and above
class staticExample {
// static block execution without main method in JDK 1.6.
static
{
System.out.println("Inside Static Block.");
System.exit(0);
}
}
Output:(In JDK 1.6)
Inside Static Block.
But from JDK 1.7 onwards the above code gives an error in output.
Output:
Error: Main method not found in class staticExample, please define the main method as:
public static void main(String args[])
or a JavaFX application class must extend javafx.application.Application
You can do this. But it is not the best idea for a couple reasons.
One is that you have hard-wired your class to whatever property files the static method is reading, complicating testing. You can't exercise the class without having the actual files present.
Another is that exception-handling in static blocks is problematic, there's no way to handle an unchecked exception thrown from a static block. See Why doesn't Java allow to throw a checked exception from static initialization block?. You would have to specifically catch everything coming out of the block, and anything that was missed couldn't be caught anywhere in the application.
Dependency injection frameworks will handle injecting this stuff into your classes for you with easier testing and no exception-handling issues.
I have a class whose initialization takes quite a bit of time; it invokes a server and that server takes several minutes to become ready.
Methods on that class aren't called for quite a while and they are always called from a class that is automatically loaded on start-up. My set-up is like this:
class SlowToStartUp {
public static void init() {
// do nothing
}
static {
initiateConnectionToServer()
}
public static V invokeServer() {
waitForServerToConnect();
return valueFromServer();
}
}
class AlwaysLoaded {
static {
SlowToStartUp.init();
}
public void someMethod() {
V v = SlowToStartUp.invokeServer();
}
This strikes me as structurally correct. If there were no init() function at all, initiateConnectionToServer() wouldn't be called until someMethod() needed the class for the first time, and then there would be an unnecessary (and in my system, unacceptable) delay.
If I put the initiateConnectionToServer() call in init(), the interface would be more fragile (since the call might be forgotten).
But now I am wondering if I have outsmarted myself. The compiler can see that init() is empty. Could it not just optimize the call away? It does not do so now, but it that guaranteed?
I tried marking init() as volatile, but that is not allowed.
I am considering putting the actual initialization into init(), making sure it is idempotent, and invoking it from a static block, just to be on the safe side, but I thought I would ask for advice first.
One alternative approach would be to refactor to a singleton class instead of a bunch of static method. The singleton will then be created at startup and your initialization code would run right away.
public class SlowPokeSingleton {
private SlowPokeSingleton() { /* execute init code */ }
// created at startup
private final static SlowPokeSingleton instance = new SlowPokeSingleton();
public static SlowPokeSingleton instance() { return instance; }
}
You will need to call instance() to make sure the instance is actually created. You can add that to your server startup to be safe.
I have a tenuous answer to my own question. The events that trigger class initialization are specified in JLS 12.4.1.
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant variable (§4.12.4).
T is a top-level class, and an assert statement (§14.10) lexically nested within T is executed.
It seems to me that a compiler that optimized away an empty static function would violate the provision I marked in bold.
Comments welcome.
I agree with Giovanni Botta:
You could use a singleton pattern instead of static methods and fetch
the singleton instance as soon as your application starts. That would
force the JVM to create the instance and thus run your initialization
code. – Giovanni Botta
Specifically:
1) Put the "time consuming" part of your initialization into a private, static "init()" method.
2) Make your class's constructor "private".
3) Instead of a constructor, provide a public static "getInstance()" method to fetch a reference to your (already-initialized) singleton instance.
4) Your other methods can be non-static, if you wish.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
If i use so
class Test {
public Test() {
System.out.println("constructor");
}
}
public class MainClass {
public static void main(String[] args) {
Test t1 = new Test();
Test t2 = new Test();
}
}
I get 2 outputs
constructor
constructor
But if I add void to constructor (public void Test()) - output is empty. Why is so strange ?
It's not strange, it's its normal behaviour. Constructor does not have a return type
public Test() {
System.out.println("constructor");
}
is a constructor, but
public void Test() {
System.out.println("constructor");
}
is a simple method that you can call using t1.Test().
This page lists the differences between constructors and methods:
1) First difference between method vs constructor in Java is that name of constructor must be same with name of the Class but there is no such requirement for method in Java. methods can have any arbitrary name in Java.
2) Second difference between method and constructor in Java is that constructor doesn't have any return type but method has return type and return something unless its void.
3) Third difference between constructor and method in Java is that Constructors are chained and they are called in a particular order, there is no such facility for methods.
4) Unlike method, constructor, yet declared in class doesn't considered as member of Class. Constructors are not inherited by child classes but methods are inherited by child classes until they are made private. on which case they are only visible in class on which they are declared. Similarly private constructor means you can not create object of that class from outside, this is one of the technique used to implement Singleton pattern in Java.
5) Another difference between method and constructor in Java is that special keyword this and super is used to call constructor explicitly. no such thing for method, they have there own name which can be used to call them.
Because if you add void to the constructor that is no longer a constructor. It's just a method that happens to have the same name as the class.
Then, you could ask "but how can I call the constructor if one doesn't exists?" Well, every class has implicit, no-args constructor.
Conclusion: constructor must not have a return type.
Constructors don't have a return type .Methods have return type. If you add void() then it turns to a method . To invoke the method you need to call it .
t1.test();
Its java language specification.
Docs saying
A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
When you write:
public Test()
{
System.out.println("constructor");
}
This is definitely a constructor. And, as you create first object of Test class by writing:
Test t1 = new Test();
This would call your constructor for the first time, and the code you have written in print statement, that is, constructor would be printed on console.
Remember, constructors are automatically called when you create an object of the class.
Second time you create object by writing:
Test t2 = new Test();
This would call the same constructor, and print the same "constructor" on screen, but it would be second time.
So you get the answer as-
constructor
constructor
In the second case, when you write:
public void test()
{
System.out.println("constructor");
}
your compiler would treat it as a method rather than a constructor.
Even if void does not return anything, it is a "return-type" and constructors can never have a return type, never.
This does not mean that they do not return you anything, but they just do not have a return type.
So, a method is not called automatically when the object of the class is created. So, you should not expect same result.
Now, you get an empty output because compiler provides a dummy/default constructor to every class, even if you do not define it. And, this default constructor would be called everytime you create a object of the class, no matter if you call it explicitly or not!
a default constructor can be thought of written somewhere as:
test() { }
so now you can imagine what happens when you create two objects, program would compile and run correctly, returning empty output to you!
I hope that helped you.
Because constructors don't have a return type. What you create when you add a void return type is a method named Test() that returns nothing.
The compiler gives you a no-arg constructor, since you didn't write any, and that does nothing because it's not the method you created.
A java constructor has the same name as the name of the class to which it belongs. Constructor’s syntax does not include a return type, since constructors never return a value.
public Test() {
System.out.println("constructor");
}
If you add return type to Constructor then it will not be a constructor no longer. It is something like a method.
This question already has answers here:
What is the difference between a static and a non-static initialization code block
(9 answers)
Closed 8 years ago.
I was looking over some code the other day and I came across:
static {
...
}
Coming from C++, I had no idea why that was there. Its not an error because the code compiled fine. What is this "static" block of code?
It's a static initializer. It's executed when the class is loaded (or initialized, to be precise, but you usually don't notice the difference).
It can be thought of as a "class constructor".
Note that there are also instance initializers, which look the same, except that they don't have the static keyword. Those are run in addition to the code in the constructor when a new instance of the object is created.
It is a static initializer. It's executed when the class is loaded and a good place to put initialization of static variables.
From http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
If you have a class with a static look-up map it could look like this
class MyClass {
static Map<Double, String> labels;
static {
labels = new HashMap<Double, String>();
labels.put(5.5, "five and a half");
labels.put(7.1, "seven point 1");
}
//...
}
It's useful since the above static field could not have been initialized using labels = .... It needs to call the put-method somehow.
It's a block of code which is executed when the class gets loaded by a classloader. It is meant to do initialization of static members of the class.
It is also possible to write non-static initializers, which look even stranger:
public class Foo {
{
// This code will be executed before every constructor
// but after the call to super()
}
Foo() {
}
}
Static block can be used to show that a program can run without main function also.
//static block
//static block is used to initlize static data member of the clas at the time of clas loading
//static block is exeuted before the main
class B
{
static
{
System.out.println("Welcome to Java");
System.exit(0);
}
}
A static block executes once in the life cycle of any program,
another property of static block is that it executes before the main method.
Static blocks are used for initializaing the code and will be executed when JVM loads the class.Refer to the below link which gives the detailed explanation.
http://www.jusfortechies.com/java/core-java/static-blocks.php
yes, static block is used for initialize the code and it will load at the time JVM start for execution.
static block is used in previous versions of java but in latest version it doesn't work.