【Java】创建对象的几种方式
合集 - Java基础(11)1.【Java】 Integer包装类缓存(cache)2.【java】Java之关于基本数据类型和引用数据类型的存放位置3.【java】ArrayList和LinkedList的区别4.【java】【集合类】HashMap 与HashTable的区别5.【Java】的四种引用类型6.【Java】创建对象的几种方式7.【java】内存溢出(OOM)8.【java】问题排查-内存溢出(OOM)-汇总指南9.【java】异常 (详解)10.【java】【集合类】HashMap之扩容原理11.【java】【集合类】ArrayList扩容机制收起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 }
}
5、构造函数对象的newInstance()方法
类Constructor也有newInstance方法,这一点和Class有点像。从它的名字可以看出它与Class的不同,Class是通过类来创建对象,而Constructor则是通过构造器。依然使用第一个例子中的Test类。
public static void main(String[] args) throws Exception { Constructor<Test> constructor; try { constructor = Test.class.getConstructor(); Test t = constructor.newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } }原文链接:https://www.cnblogs.com/zzsuje/p/18186518 标签:java,05,创建对象,value,几种,Java,MyClass,public,out From: https://www.cnblogs.com/sunny3158/p/18459814