用 Java 创建对象的不同方法
原文: https://javabeginnerstutorial.com/core-java-tutorial/different-ways-to-create-an-object-in-java/
您必须知道使用new关键字创建类的对象,但这不是创建对象的唯一方法。
还有其他几种创建类对象的方法:
- 使用
new关键字 - 使用新实例(反射)
- 使用克隆
- 使用反序列化
- 使用
ClassLoader - …不知道了 🙂
使用new关键字
使用new关键字是创建对象的最基本方法。 new关键字可用于创建类的对象。
public class ObjectCreationExample {public static void main(String[] args) {// Here we are creating Object of JBT using new keywordJBT obj = new JBT();}}class JBT{String Owner;}
使用newInstance(反射)
您是否曾经尝试使用 Java 中的 JDBC 驱动程序连接到数据库? 如果您的回答是肯定的,那么您必须已经看到“Class.forName”。 我们还可以使用它来创建类的对象。 Class.forName实际上是在 Java 中加载该类,但未创建任何对象。 要创建对象,必须使用Class类的newInstance方法。
/** Here we will learn to create Object of a class without using new Operator.* But newInstance method of Class class.*/class CreateObject {public static void main(String[] args) {try {Class cls = Class.forName("JBTClass");JBTClass obj = (JBTClass) cls.newInstance();JBTClass obj1 = (JBTClass) cls.newInstance();System.out.println(obj);System.out.println(obj1);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}}class JBTClass {static int j = 10;JBTClass() {i = j++;}int i;@Overridepublic String toString() {return "Value of i :" + i;}}
如果要以这种方式创建对象,则类需要具有公开的默认构造器。
使用Clone
我们还可以使用Clone()方法创建现有对象的副本。
/** Here we will learn to create an Object of a class without using new Operator.* For this purpose we will use Clone Interface*/class CreateObjectWithClone {public static void main(String[] args) {JBTClassClone obj1 = new JBTClassClone();System.out.println(obj1);try {JBTClassClone obj2 = (JBTClassClone) obj1.clone();System.out.println(obj2);} catch (CloneNotSupportedException e) {e.printStackTrace();}}}class JBTClassClone implements Cloneable {@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}int i;static int j = 10;JBTClassClone() {i = j++;}@Overridepublic String toString() {return "Value of i :" + i;}}
关于克隆的其他说明
- 在这里,我们正在创建现有对象而不是任何新对象的克隆。
- 克隆方法在
Object类中声明为受保护的。 因此,只能在子类或同一包中对其进行访问。 这就是为什么它在类上被覆盖的原因。 - 类需要实现
Cloneable接口,否则它将引发CloneNotSupportedException。
使用对象反序列化
对象反序列化也可以用于创建对象。 它产生与序列化对象相反的操作。
使用ClassLoader
我们也可以使用ClassLoader创建类的对象。 这种方式与Class.forName选项相同。
/** Here we will learn to Create an Object using Class Loader*/public class CreateObjectWithClassLoader {public static void main(String[] args) {JBTClassLoader obj = null;try {obj = (JBTClassLoader) new CreateObjectWithClassLoader().getClass().getClassLoader().loadClass("JBTClassLoader").newInstance();// Fully qualified classname should be used.} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();}System.out.println(obj);}}class JBTClassLoader {static int j = 10;JBTClassLoader() {i = j++;}int i;@Overridepublic String toString() {return "Value of i :" + i;}}