1.使用new
关键字
使用 new
关键字创建对象,实际上是做了两个工作,一是在内存中开辟空间,二是初始化对象。但是new
关键字只能创建非抽象对象。
2. 使用反射创建对象
反射是对于任意一个正在运行的类,都能动态获取到他的属性和方法。反射创建对象分为两种方式,一是使用Class类的new Instance()
方法,二是使用Constructor类的new Instatnce()
方法。
两者区别在于:
Class.newInstance() 只能够调用无参的构造函数,即默认的构造函数;
Constructor.newInstance() 可以根据传入的参数,调用任意构造构造函数。
3. 使用clone方法
要拷贝的对象需要实现Cloneable类,并重写clone()方法。
4. 使用反序列化方式
当序列化和反序列化一个对象,jvm会给我们创建一个单独的对象。在反序列化时,jvm创建对象并不会调用任何构造函数。为了反序列化一个对象,需要让类实现Serializable接口。然后在使用new ObjectInputStream().readObject()
来创建对象。
下面demo:
public class Order implements Cloneable, Serializable{
private String code;
private String name;
@Override
protected Object clone() throws CloneNotSupportedException {
return (Order)super.clone();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Order order = (Order) o;
if (code != null ? !code.equals(order.code) : order.code != null) return false;
return name != null ? name.equals(order.name) : order.name == null;
}
@Override
public int hashCode() {
int result = code != null ? code.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
以上内容转载自:
https://blog.csdn.net/syp_24/article/details/73740919
如何使用反射机制为私有变量进行赋值?
``` package cn.itctas.thread.create;import java.lang.reflect.Field;
//使用反射机制为private属性进行赋值
public class Reflax3 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, InstantiationException {
//获取user的class对象
Class userClass = (Class) Class.forName(“cn.itctas.thread.create.User”);
User user = userClass.newInstance();
//获取指定的Field
Field fieldId = userClass.getDeclaredField(“age”);
//允许对该field进行反射,若不设置则会抛出异常
fieldId.setAccessible(true);
// fieldId.set(obj, value); 对哪个对象进行赋值,将字段赋值为 什么?
fieldId.set(user, 18);
Field fieldName = userClass.getDeclaredField("name");
fieldName.setAccessible(true);
fieldName.set(user, "你好");
System.out.println(user);
}
}
</br>
</br>
</br>
<h3>反射创建api</h3>
方法名称 作用
getDeclaredMethods [] 获取该类的所有方法
getReturnType() 获取该类的返回值
getParameterTypes() 获取传入参数
getDeclaredFields() 获取该类的所有字段
setAccessible(true) 允许访问私有成员