I have this code
MyClassloader loader = new MyClassloader();
Class c = loader.loadClass(classToLoad);
Thread.currentThread().setContextClassLoader(loader);
MyClass myClass = (MyClass) c.newInstance();
And classloader code is
public MyClassloader) throws IOException {
super(Thread.currentThread().getContextClassLoader());
}
The class loading works fine the problem is that static variables are not isolated, so if inside the MyClass a static variable is set all other MyClass instances get the same value.
In what can a static variable be isolated?
You delegate to the same class loader. So you will see no difference.
What should yo do? Implement class loading in your class loader, don't just delegate. For instance, inherit your class loader from URLClassLoader, initialize it properly (it means, provide a valid class path to your class loader to initialize it). Then you will see, that classes loaded by you class loader are not euqal to the classes loaded by the standard class loader, and as a consequence, their static members will be different.
Often the context class loader is inherited from URLClassLoader and thus you don't have to spend much time configuring class path for it. Instead, to initialize you class loader you can just reuse the URLs of the context class loader, as follows:
public class MyIndependentClassLoader extends URLClassLoader {
public MyIndependentClassLoader(){
super(((URLClassLoader) Thread.currentThread().getContextClassLoader()).getURLs());
}
}
Now you can use your class loader and check static members.
What is the difference between this approach and the original approach?
You know that classes are also objects (of special type): they have their own member variables, name, serialVersionUID, annotationData, etc., and their own methods, newInstance(), getFields(), getMethods(), etc. When you call
Class c = loader.loadClass("com.my.package.MyClassX");
you get c, this is an object that describes the loaded class "some class name". This c not only allows to create instances, but holds also all static members.
In your code: Your class loader does not load class directly. Instead, it delegates to the context class loader. That's why if you compare two loaded classes
Class c = loader.loadClass("com.my.package.MyClassX");
Class ct = Thread.currentThread().getContextClassLoader().loadClass("com.my.package.MyClassX");
you will see, that c and ct is the same object. If you call c.equals(ct), it will give you true. And if you call c == ct, it will also give you true. It means, this is the same class instance. That's why - naturally - if you check static variables, they will be the same. If you change static variable in one class, it will also be changed in another class, and vice versa.
In my code: The essential difference is, that the class loader loads classes itself. It does not delegate it to other class loader. I suggested to extend it from URLClassLoader to simplify our implementation (otherwise you would have implement from scratch dealing with class path, directories, jars, visibility, caching, etc.). And to avoid adding each class path element step by step I suggested to use the same class path (the same list of directories, jars, etc.) as the context class loader. So our class loader will be able to find the same classes as the context class loader.
Now check the class that this class loader loads. Let's call it ci:
Class ci = new MyIndependentClassLoader().loadClass("com.my.package.MyClassX");
If you compare these classes, you will see that c.equals(ci) gives false. Means, they are different. That's why they have also independent static members. If you change static member in one class, ct, it will not change in the other, ci, and vice versa.
I'm following this tutorial for create Singleton and the owner have comment when the method below http://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples
public class EagerInitializedSingleton {
private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();
//private constructor to avoid client applications to use constructor
private EagerInitializedSingleton(){}
public static EagerInitializedSingleton getInstance(){
return instance;
}
}
If your singleton class is not using a lot of resources, this is the
approach to use. But in most of the scenarios, Singleton classes are
created for resources such as File System, Database connections etc
and we should avoid the instantiation until unless client calls the
getInstance method.
The Problem Is:
They say we should avoid the instantiation until unless client calls the getInstance method
BUT as I know in this code the instantiation (of object instance) always happened when class EagerInitializedSingleton load, and EagerInitializedSingleton just only load when we call EagerInitializedSingleton.getInstance()
=> The instantiation will happened on time with getInstance() and never before getInstance()
Reference:
Static variables are initialized only once , at the start of the execution(when the Classloader load the class for the first time) .
(from https://stackoverflow.com/a/8704607/5381331)
So when are classes loaded?
There are exactly two cases:
- when the new bytecode is executed (for example, FooClass f = new FooClass();)
- and when the bytecodes make a static reference to a class (for example, System.out)
(from http://www.javaworld.com/article/2077260/learn-java/learn-java-the-basics-of-java-class-loaders.html)
Am I wrong or correct. Please give me some sugestion.
In this case with that specific code, you are probably correct.
However, if you had static methods of EagerInitializedSingleton, or static non-final members of EagerInitializedSingleton referenced somewhere in your code base prior to the invocation of getInstance, the instance variable of EagerInitializedSingleton would initialize.
Same with a reflective invocation of Class.forName on your EagerInitializedSingleton class.
Note (and forgive the obvious here) that there are alternative ways of declaring a singleton, including lazy-initialization or enums.
I think the problem is when a class gets loaded without the need to get the instance, but for some other reason. You assume that class will be used the first time when user will want to get an instance of that singleton, but it may happen for some other reason, he may just call a class loader for something, or use some 3rd party software to validate a class, anything that comes to mind that involves loading a class but not getting an instance of a singleton.
They say we should avoid the instantiation until unless client calls
the getInstance method
The solution is lazy loading.
From wikipedia, Initialization-on-demand holder idiom
When the class Something is loaded by the JVM, the class goes through
initialization. Since the class does not have any static variables to
initialize, the initialization completes trivially. The static class
definition LazyHolder within it is not initialized until the JVM
determines that LazyHolder must be executed. The static class
LazyHolder is only executed when the static method getInstance is
invoked on the class Something, and the first time this happens the
JVM will load and initialize the LazyHolder class.
public class Something {
private Something() {}
private static class LazyHolder {
private static final Something INSTANCE = new Something();
}
public static Something getInstance() {
return LazyHolder.INSTANCE;
}
}
I'm reading Java tutorials from the begining and I have a question about static keyword on fields or variables. As Java said here:
Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances.
With that, I guess that if you have an object (in this case, an instance of the class Bicycle) and a field inside of it that its static then, independently of if you are refearing to bicycle1 or bicycle2, the field that its static will have the same value. Am I wrong or I understand it well?
I mean, if I have:
Bicycle bicycle1 = new Bicycle();
Bicycle bicycle2 = new Bicycle();
and in the class Bicycle I have a static field like:
class Bicycle{
static int gears;
//Methods to set and get gears
}
And in the bicycle1 I set the value of gears to seven:
bicycle1.setGears(7);
then if I try to get the value of gears in bicycle2 I should get the same value as I set on bicycle1, right?
System.out.println(bicycle2.getGears()); //7
Well, here is where I have the doubt because as Java said in the quote that I put above:
this tells the compiler that there is exactly one copy of this variable in existence
Where is this copy stored? How the objects access to that copy? When is this copy created?
Where is this copy stored?
The copy (static variable) is stored in the Permanent Generation section, but if you use Java8 the Permanent Generation section no longer exists.
The static variables and static methods are part of the reflection data which are class-related data and not instance-related.
How do the objects access that copy?
Every instance of class (object) that you have created has a reference to the class.
When is this copy created?
It is created at runtime when the class is loaded: this is done by the classloader of the JVM when the class is first referenced.
Static variables belong to the class, and not to instances of the class.
Your intuition is right - you have only one copy regardless of how many object you create.
You can access a static variable using the name of the class, like in this example:
class Static {
static int staticField;
}
public class UseStatic {
public static void main(String[] args) {
System.out.println(Static.staticField);
}
}
The static fields are useful to create some kind of class constants.
Finally, to easily initialize a static field of a specific class you can use Static Initialization Blocks.
Sources: University course on java, java official documentation
With that, I guess that if you have an object (in this case, an
instance of the class Bicycle) and a field inside of it that its
static then, independently of if you are refearing to bicycle1 or
bicycle2, the field that its static will have the same value. Am I
wrong or I understand it well?
When you instantiate a class in Java for the first time, the JVM creates two things:
an instance. A set of non-static fields is allocated onto the heap for each of the instances that you create. These instance fields are separate from all other instances (and are used to represent their object's state).
a Class object. Every class in Java has one, and only one, Class object ... no matter how many instances of it that are created. For example, the Class object for class String is Class<String> (which is expressed as a literal as String.class). You can think of the static fields of a class as belonging to the Class object. The lifecycle of Class objects is independent of the lifecycle of class instances; Class objects exist for as long as the JVM process is running (therefore, their static fields also exist that long).
Since a class has only one Class object, and since all instances of a class share that same Class object, the static fields of a class are shared by all the class instances that exist.
In general, it is useful to think of the static keyword as meaning "independent of any instance":
a static field belongs to the Class object and not to any instance
a static method is invoked through the Class object and has no direct access to any instance
a static member class instance is not dependent on any other instance
static variables in java are stored in the class, you don't need to create a instance of it to access them.
class Bicycle{
public static int gears = 7;
//Methods to set and get gears
}
You can access the static method like this
Bicycle.gears;
So, there's just one Bicycle class declared on java, when you instantiate a class it's create one instance of bicycle with all static attributes declared.
Where is this copy stored?
Static variables are stored in some static storage (in permgen, I believe), you should not bother about it.
When is this copy created?
They are created when class is accessed first time (loaded by class loader) and never deleted (unless class is unloaded)
How the objects access to that copy?
Instance has reference to its class, and class has reverence to all its variables. How exactly C structures are laid in memory is implementation-specific detail.
Since static vars are bound to class, not instance, you do not even need to instantiate class to access them. MyClass.myStaticVar is ok.
A little doubt with java and static variables. I have something like that, and the question is: MyObject() constructor runs only once or every time I create a new instance of MyClass?
public class MyClass{
static MyObject obj = new MyObject();
...
Thanks!
MyObject() constructor runs only once or every time I create a new instance of MyClass?
It runs only once when the execution process(class initialization ) starts and shared (A single copy) across all the instances.
A static initializer declared in a class is executed when the class is initialized (§12.4.2). Together with any field initializers for class variables (§8.3.2), static initializers may be used to initialize the class variables of the class.
http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.7
Yes, it will only create it once! A static field is common among all your instances. Specifically, it's created when that class is initialized.
It is executed only once during the class loading process.
I do not understand why the main method has to be static. I understand static variables but static methods are difficult for me to grasp. Do static method exists so that one can create two methods with the same name in two different classes that won't clash with each other?
Also, I don't understand why I can't create a static constructor.
Could anyone help explain this concept?
Java has [static constructors] static initialization blocks which can be viewed as a "static constructor":
class Foo {
static String Bar;
static {
// "static constructor"
Bar = "Hello world!";
}
}
In any case, the only method in the main class which must be static is the main method. This is because it is invoked without first creating an instance of the "main class". A common technique, and the one I prefer, is to quickly get out of static context:
class Main {
int argCount;
// constructor
public Main (String[] args) {
// and back to boring ol' non-static Java
argCount = args.length;
}
void runIt () {
System.out.println("arg count: " + argCount);
}
// must be static -- no Main instance created yet
public static void main (String[] args) {
Main me = new Main(args);
me.runIt();
}
}
Also, static has nothing to do with "name clashes". A static method (or variable) is simply a method (or variable) that is not associated with a specific instance of a type. I would recommend reading through the Classes and Objects Java Tutorial and the section Understanding Instance and Class Variables.
Happy coding.
I am sharing one of the reason "why not a java constructor be static".
Simply to say, "A java constructor is always non static" because,
The purpose of the constructor is only to initialize/construct the object, and to make inheritance possible. To do these we need to use the two useful java keywords (cum non-static variables) such as this and super.
We will use 'this' to initialize the object.
We/Java will use super(ofcourse super()) to invoke super class constructor so that super object(or Object class) created first then the child object(hence the inheritance)
If the constructor is static then we cant use that two keywords(non-static variables) inside the constructor(As we know non-static stuff cant be referenced from static context)
So java constructors should not static.
Static methods belong to a class, not an object. The main method must be static because it is called first, before any other code has executed to instantiate any objects. It provides an entry point to the program. Static methods are called from outside of the container of an object. The same is true of static class variables. Only one copy exists for the entire class, as opposed to a member variable, which is created once for each object created from a class. They are used to store data for the class, such as the number of object instances have been created and not destroyed. This data belongs with the class. A good example of a static method is in the singleton pattern, where the constructor is private and can only be accessed by a static member function. A function outside the class would be unable to replicate this functionality. This method acts on class data and objects, so logically belongs to the same class. This all boils down to encapsulation. A class is responsible only for itself and knows only itself.
On the other hand, object methods are meant to operate on the data associated with a single instance of a class, an object. Constructors are the code that is used to initialize an object and set it's data to an initial state. They are executed immediately (and automatically) after the memory has been allocated to store a new object. Even if you do not explicitly define a constructor, a kind of "default constructor" is executed in order to map the object's member variables and the object's method code to the new object.
Hope this helps.
Constructor is used to create Objects.
Static is generally which is same for all objects.
So, if we have had static constructors creation of one object would affect all the other existing objects.
Static methods only reference to static variables. Therefore all the initial parameters which you are giving to create an object would change for all objects. It is no point creating similar objects for no use.
Hope this helps.... :)
Constructor is the property of an object while static has nothing to do with object. That's why there is nothing like static constructor. But we have static block to do the similar task as constructor i.e. initialization of fields etc.
On page 272 of Thinking In Java, 4th Edition, by Bruce Eckel, it says:
²The constructor is also a static method even though the static keyword is not explicit. So to be precise, a class is first loaded when any of its static members is accessed.
A little bit more context.
... the compiled code for each class exists in its own separate file. That file isn't loaded until the code is needed. In general you can say "class code is loaded at the point of first use." This is usually when the first object of that class is constructed, but loading also occurs when a static field or static method is accessed.²
This makes a lot of sense, if you think about the rule that says that a static method can't use non-static methods of the same class. I had this doubt a couple weeks ago when I couldn't understand how, using the Singleton Pattern, you could access the constructor inside the static method that is used to create a new instance of that class. Today I was flipping through the book and I came across this explanation.
It also makes sense in a way that, if the constructor wasn't static, you'd first need an instance of that class to be able to access it, but I guess this could spark up the old discussion about the chicken or the egg.
Hope it helped!
Constructors are neither entirely static (class level) or entirely non-static (instance level).
Unlike instance methods, constructors are not inherited.
Unlike static methods, a constructor can refer to this.
So, why can't you declare a constructor static?
Well, my take is that a (redundant) static keyword would be confusing and would not serve any purpose. Therefore they decided not to allow it.
The explanation that static initialization blocks can be viewed as constructors is (IMO) conceptually wrong. (It is analogous to saying that an instance initialization block is a regular constructor. Which is equally wrong.)
The key distinctions between static initialization and construction1 are:
static initialization happens at an indeterminate time2; there is no equivalent to new for class initialization,
there is no straight-forward way to pass (constructor) parameters to the initialization code
there is no practical way to recover from errors occurring during static initialization.
1 - Hypothetically, if class initialization was explicit, then it would make sense to have static constructors. But the downsize would be that applications would need to explicitly "construct" all of the classes that they used ... which would be horrible.
2 - You have a degree of control if you load a class dynamically, but even then if the class has already been loaded and initialized in the current classloader, then attempting to control initialization will fail.
I do not understand why the main method has to be static.
It has to be if you want the main method to act as an entrypoint for your application.
The problem is that if main was an instance method, then there would need to be an instance of your entrypoint class to call the main method on. But how do you create it? Which constructor would you choose? What if there was no public constructor?
The bottom line is that this is the way that Java was designed ... back in the 1990's ... and so far they have not seen the need to change this.
a) static is belongs to class not object and constrictor is called during the object creation.
b) if we create a constructor as static then it can't be call by subclass as static is accessible only from class not by sub class. So during subclass object creation it can't be call the present class constructor.
c) static members are executed first in the program, so if we declare constructor as static then it will executed before object creation which is oppose the purpose of the constructor.
If we declare constructor as static then it will give compile time error.
If we want to initialize static member then need to use of static block.
I wrote a simple example as an answer to a related question yesterday which may help make things more understandable: what's the point of java constructor?
The point of Static methods is that they can be called without creating an instance of a class, while "normal" instance methods are related to an instance, and can not be called without one.
Since the Main method of the Main class is the entry point of the program, no instance can possibly have been created yet, so naturally, you can not access it via an instance. Therefore, it is Static, so it can be run as the start of the program.
Just take a look on this link, it will definately help you to understand:
Why can't make a constructor static?
AND
Constructor is called at Run-time when we create Objects.
Static is same for all objects but all objects have their own state and properties.
So, if we have had static constructors creation of one object would affect all the other existing objects.
Note: static is class level while constructors related to the objects.
e.g.
public class Foo
{
String name;
int id;
// define constructors
Foo (String name, int id)
{
this.name = name;
this.id = id;
}
p s v m(String[] arg)
{
Foo f1 = new Foo("Amit",001);
Foo f2 = new Foo("Rahul",002);
}
}
If we create static constructor then both objects(f1 also) will contain the last updated value regarding name and id as Rahul and 002.
A constructor cannot be static, because in an OO language, the process for creating an object is as follows:
allocate the object
call the constructor to initialise the newly-allocated object
Constructors are not used anywhere else (and a type-safe language should enforce this), so it follows that a constructor will always be called in a non-static context.
If a constructor were static, it would not receive a reference to the newly-allocated object, and thus would not be able to initialise it.
Thus, a constructor can always be non-static (as it is always called from a non-static context) and must always be non-static (otherwise it would be unable to perform its task).
The main(String[]) method has a specific prototype that is dictated by how the Java runtime environment works. When you invoke java MyApplication from the command line, the Java VM will look for a static main(String[]) method contained in that class in order to execute the application. If that method is not found, then the Java VM can't run the class as an application. That's just how the language is defined. It also means that the Java VM doesn't create an instance of your application class in order to run it.
Now, if you want your class to be usable either as a standalone application or as an instance that's created by something else, then you can have your class implement the Runnable interface, and also provide a main method that executes the run method on a new instance.
public class MyRunnableThing implements Runnable
{
// Define whatever variables your runnable thing needs here as
// private instance fields.
/** Fulfills requirements of Runnable interface. */
public void run()
{
System.out.println( "I'm running..." ) ;
}
/** Also makes the class runnable from the console. */
public static void main( String[] args )
{
MyRunnableThing runMeNow = new MyRunnableThing() ;
runMeNow.run() ;
}
}
Now any class could potentially create an instance of MyRunnableThing and use its run() method to produce the same behavior that would have been seen by executing java MyRunnablething.
See also: Working with Static Constructor in Java. Some highlights from that Q&A:
A constructor is used to create an instance of the class, so it's an instance method, not a static method.
You can create a static method that creates an instance of the class, using the constructor. This is how the trendy new "builder" classes work.
You can create a static method that returns a persistent, unique singleton instance.
If your class has static members, then you can create a static initializer to initialize the values of those members.
The purpose of Constructor is to Construct an Object i.e. to initialize class's instance variables either their default values or by their initialized values. non-static Instance variables can't be accessed by static methods . So constructor is not static.
The method declared as static requires no object creation .As we don't create object for the main method it is declared as static.
constructor is implicitly called to initialize an object, so there is no purpose in having a static constructor.
First, the key word static means that everything marked static must be the class-level thing and belongs to the class only.While constructors belong to object and they may usually be called when we use the new operator.So we now know that a constructor is not even a class property,how could we possibly mark it as static?
Second,static constructor violates the whole purpose of inheritance in java.Every time just before we create an subclass object ,JVM automatically calls the superclass constructor to make it ready for the subclass object to be created.But if we mark the constructor static,the subclass will not be able to access the constructor of its superclass because it's marked static thus belongs to class only.
Java does not permit to declare a constructor as static. Following are the reasons.
Static means for the same class. i.e, static methods cannot be inherited.
With static, "this" reference (keyword) cannot be used. "this" is always linked to an object. A constructor always belongs to some object.
If a constructor is static, an object of subclass cannot access. If static is allowed with constructor, it is accessible within the class but not by subclass.
Static Belongs to Class, Constructor to Object
We know that static methods, block or variables belong to the class. Whereas a Constructor belongs to the object and called when we use the new operator to create an instance. Since a constructor is not class property, it makes sense that it’s not allowed to be static.