1. Create a new Object
Create an object using the new keyword should be the most common way, but we should know, use new to create an object will increase the degree of coupling. No matter what framework to use, should reduce the use of new in order to reduce the degree of coupling.
public class Hello
{
public void sayWorld()
{
System.out.println("Hello world!");
}
}
public class NewClass
{
public static void main(String[] args)
{
Hello h = new Hello();
h.sayWorld();
}
}
2. Use reflection mechanism to create objects
Using the newInstance method of class Class
public class NewClass
{
public static void main(String[] args)
{
try {
Class heroClass = Class.forName("test.Hello");
Hello h = (Hello) heroClass.newInstance();
h.sayWorld();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
}
}
Constructor methods using class newInstance
public class NewClass
{
public static void main(String[] args)
{
try {
//获取类对象
Class heroClass = Class.forName("yunche.test.Hello");
//获取构造器
Constructor constructor = heroClass.getConstructor();
Hello h =(Hello) constructor.newInstance();
h.sayWorld();
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
3. Using clone
clone, you need to have a memory of the source object is allocated, when you create a new object, first of all should be allocated as big as a source and target memory space.
To call the clone method needs to implement the Cloneable interface, because the clone method is protected, so modify the Hello class.
public class Hello implements Cloneable
{
public void sayWorld()
{
System.out.println("Hello world!");
}
public static void main(String[] args)
{
Hello h1 = new Hello();
try {
Hello h2 = (Hello)h1.clone();
h2.sayWorld();
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
}
}
}
4. The use of serialization mechanism
When using serialization, to implement implements Serializable, the object is serialized to a disk, while the use of deserialization may be converted to an object on the disk into memory.
public class Serialize
{
public static void main(String[] args)
{
Hello h = new Hello();
//准备一个文件用于存储该对象的信息
File f = new File("hello.obj");
try(FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis)
)
{
//序列化对象,写入到磁盘中
oos.writeObject(h);
//反序列化对象
Hello newHello = (Hello)ois.readObject();
//测试方法
newHello.sayWorld();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}