我知道"new“关键字和class.forName()的用法,但我知道我们可以在编写方法定义时创建对象。比如methodName(对象创建);
发布于 2016-06-24 11:19:35
这些是创建对象的所有方法。
方法1:
使用新关键字。这是在java中创建对象的最常见方法。几乎99%的对象是以这种方式创建的。
Object object = new Object();方法2:
使用Class.forName()。Class.forName()为您提供类对象,这对于反射非常有用。这个对象所拥有的方法是由Java定义的,而不是由编写类的程序员定义的。每个班级都是一样的。对该类调用newInstance()将为您提供该类的一个实例(即newInstance,它等同于调用新的ExampleClass()),您可以在该实例上调用该类定义的方法,访问可见字段等。
CrunchifyObj object2 = (CrunchifyObj)
Class.forName("crunchify.com.example.CrunchifyObj").newInstance();Class.forName()总是使用调用方的ClassLoader,而ClassLoader.loadClass()可以指定不同的ClassLoader。我相信Class.forName也会初始化已加载的类,而ClassLoader.loadClass()方法并不会立即这样做(直到第一次使用它时才会初始化)。
方法3 :
使用克隆()Object::clone()可用于创建现有对象的副本。
CrunchifyObj secondObject = new CrunchifyObj();
CrunchifyObj object3 = (CrunchifyObj) secondObject.clone();方法4:
采用Class::newInstance()方法。见Oracle教程。
Object object4 = CrunchifyObj.class.getClassLoader().loadClass("crunchify.com.example.CrunchifyObj").newInstance();方法5:
使用对象反序列化。对象反序列化只不过是从它的串行化表单创建一个对象。
// create a new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream("crunchify.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);
// write something in the file
oout.writeObject(object3);
oout.flush();
// create an ObjectInputStream for the file we created before
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("crunchify.txt"));
CrunchifyObj object5 = (CrunchifyObj) ois.readObject();方法6:
使用java.lang.reflect包中的java.lang.reflect类,这是Java反射工具的一部分。
Class clazz = CrunchifyObj.class;
Constructor crunchifyCon = clazz.getDeclaredConstructors()[0];
CrunchifyObj obj = (CrunchifyObj) crunchifyCon.newInstance();https://stackoverflow.com/questions/38011767
复制相似问题