1.new创建新的对象
String str = new String("str");
2.通过Java的反射机制
public static void main(String[] args) throws Exception { // 获取类的Class对象 String str = (String)Class.forName("java.lang.String").newInstance();
System.out.println(str);
}
3.通过clone机制(克隆机制)
=========================Myclass.java===========================================
public class MyClass implements Cloneable { private int value; public MyClass(int value) { this.value = value; } public int getValue() { return value; } @Override public MyClass clone() throws CloneNotSupportedException { return (MyClass) super.clone(); } } ===========================Main.java============================================= public class Main { public static void main(String[] args) throws CloneNotSupportedException { MyClass obj1 = new MyClass(10); MyClass obj2 = obj1.clone(); System.out.println(obj1.getValue()); // 输出:10 System.out.println(obj2.getValue()); // 输出:10 } }
4.通过序列化机制
通过序列化机制来创建新的对象。序列化是将对象转换为字节流的过程,以便可以将其存储在磁盘上或通过网络传输。反序列化则是将字节流转换回对象的过程。
===================================================================================================
import java.io.*; public class MyClass implements Serializable { private int value;
public MyClass(int value) { this.value = value; } public int getValue() { return value; } private void writeObject(ObjectOutputStream out) throws IOException { out.writeInt(value * 2); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { value = in.readInt(); } } =================================================================================================== public class Main { public static void main(String[] args) throws IOException, ClassNotFoundException { MyClass obj1 = new MyClass(10); FileOutputStream fileOut = new FileOutputStream("obj1.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(obj1); out.close(); fileOut.close(); FileInputStream fileIn = new FileInputStream("obj1.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); MyClass obj2 = (MyClass) in.readObject(); in.close(); fileIn.close(); System.out.println(obj1.getValue()); // 输出:10 System.out.println(obj2.getValue()); // 输出:20 } }
标签:Java,String,创建对象,value,new,MyClass,public,四种,out From: https://www.cnblogs.com/lsj4/p/17555188.html