We can create an object in 5 ways.
1. Using new keyword
This is the most common way to create an object in Java.
If we know the name of the class and if it has a public default constructor.
1. Using new keyword
This is the most common way to create an object in Java.
MyObject object = new MyObject();2. Using Class.forName()
If we know the name of the class and if it has a public default constructor.
MyObject object = (MyObject) Class.forName("com.szimi.MyObject").newInstance();
3. Using clone()
If we want to create a copy of an existing object.
MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();
4. Using object deserialization
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();
5. Using class loader
this.getClass().getClassLoader().loadClass("com.szimi.MyObject").newInstance();
Nincsenek megjegyzések:
Megjegyzés küldése