面试被问到此问题,回答的不够完全,故自己网上搜索总结一下,如有不足之处请指出,谢谢。
1、通过java关键字NEW创建对象
最简单最常用的创建对象方式,包括无参的和有参的构造函数。
例如:
通过NEW关键字创建方式:
Test test = new Test();//通过无参构造函数创建
Test test1 = new Test(this);//this表示上下文context
//Test对象
public class Test{
public Test(){
}
public Test(Context context){
}
}
2、通过工厂方法返回对象
如:String str = String.valueOf(10);
3、通过反射手段返回对象
- 调用java.lang.Class类的newInstance()方法
//newInstance
String className = "com.song.Test";//reference
try {
Test test2 = (Test)Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//或者
try {
Test test3 = Test.class.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
- 调用java.lang.reflect.Constructor类的newInstance()方法
try {
//拿到Constructor构造器
Constructor<Test> constructor = Test.class.getConstructor();
try {
//通过构造器的newInstance返回对象
Test Test4 = constructor.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
4、通过对象的clone()方法返回对象
需要满足一下两点条件:
1)、需实现Cloneable接口
2)、覆盖clone方法
例如:
//CLONE
try {
Test test5 = (Test)test.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
//Test
public class Test implements Cloneable{
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public Test(){
}
public Test(Context context){
}
}
5、通过I/O流(反序列化)返回对象
调用java.io.ObjectInputStream
对象的 readObject()
方法返回对象
* 需要实现Serializable接口
public class Test implements Serializable{
public Test(){
}
public Test(Context context){
}
}
例如;
// Serialization
String fileName = "D:/serializaton.txt";//文件的具体路径
try {
ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(fileName));
o.writeObject(test);
o.close();
} catch (IOException e) {
e.printStackTrace();
}
// Deserialization
try {
ObjectInputStream i = new ObjectInputStream(new FileInputStream(fileName));
try {
//通过readObject()方法返回对象
Test test6 = (Test)i.readObject();
i.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
参考文章
https://www.cnblogs.com/wxd0108/p/5685817.html
https://www.cnblogs.com/baizhanshi/p/5896092.html
https://blog.csdn.net/coffee801/article/details/71080634
https://blog.csdn.net/hustzw07/article/details/72518298