Had a conversation with a coworker the other day about this.
There's the obvious which is to use a constructor, but what other ways are there?
Had a conversation with a coworker the other day about this.
There's the obvious which is to use a constructor, but what other ways are there?
new
operator (thus invoking a constructor)clazz.newInstance()
(which again invokes the constructor). Or byclazz.getConstructor(..).newInstance(..)
(again using a constructor, but you can thus choose which one)To summarize the answer - one main way - by invoking the constructor of the object's class.
Update: Another answer listed two ways that do not involve using a constructor - deseralization and cloning.
Other ways if we are being exhaustive.
anewarray
,multianewarray
,newarray
ornew
. These can be added using libraries such as ASM or BCEL. A version of bcel is shipped with Oracle's Java. Again this doesn't call a constructor, but you can call a constructor as a seperate call.Yes, you can create objects using reflection. For example,
String.class.newInstance()
will give you a new empty String object.Depends exactly what you mean by create but some other ones are:
You can also clone existing object (if it implements Cloneable).
Method 1
Using new keyword. This is the most common way to create an object in java. Almost 99% of objects are created in this way.
Method 2
Using Class.forName(). Class.forName() gives you the class object, which is useful for reflection. The methods that this object has are defined by Java, not by the programmer writing the class. They are the same for every class. Calling newInstance() on that gives you an instance of that class (i.e. callingClass.forName("ExampleClass").newInstance() it is equivalent to calling new ExampleClass()), on which you can call the methods that the class defines, access the visible fields etc.
Class.forName() will always use the ClassLoader of the caller, whereas ClassLoader.loadClass() can specify a different ClassLoader. I believe that Class.forName initializes the loaded class as well, whereas the ClassLoader.loadClass() approach doesn’t do that right away (it’s not initialized until it’s used for the first time).
Another must read:
Java: Thread State Introduction with Example Simple Java Enum Example
Method 3
Using clone(). The clone() can be used to create a copy of an existing object.
Method 4
Using newInstance() method
Method 5
Using Object Deserialization. Object Deserialization is nothing but creating an object from its serialized form.