示例对象
public class People { private String name; private String address;public People() { } public People(String name, String address) { this.name = name; this.address = address;} public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address;} public void setAddress(String address) { this.address = address;}}
构造器创建对象
People people= new People("lili","china");
利用class的反射机制
ClasspeopleClass = People.class;//获得People的Class实例对象People people = (People)peopleClass.newInstance();//Classclazz =Class.forName("People");People people = (People)clazz.newInstance();
这种方式适用于有无参构造器的类
利用序列化的方式构造实例对象
publicclassCreateFourimplementsSerializable{publicstaticvoidmain(String args[]){ CreateFour fCreateFour =newCreateFour(); ObjectOutputStream objectStream;try{ objectStream =newObjectOutputStream(newFileOutputStream("res/obj.txt")); objectStream.writeObject(fCreateFour); ObjectInputStream objectInputStream =newObjectInputStream(newFileInputStream("res/obj.txt")); CreateFour cloneFour = (CreateFour) objectInputStream.readObject(); }catch(FileNotFoundException e) {// TODO Auto-generated catch block e.printStackTrace(); }catch(IOException e) {// TODO Auto-generated catch block e.printStackTrace(); }catch(ClassNotFoundException e) {// TODO Auto-generated catch block e.printStackTrace(); } } }
这种方式前提是该类必须要实现Serializable
利用Object的clone方法
public class CreateFour implements Cloneable {
public static void main(String args[]) {
CreateFour f = new CreateFour();
try {
CreateFour cloneObject = (CreateFour) f.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
该类必须实现Cloneable接口,不然会抛出异常CloneNotSupportedException
使用Objenesis来实例化对象
Objenesis objenesis= new ObjenesisStd();ObjectInstantiator instantiator= objenesis.getInstantiatorOf(People.class);People people= (People) instantiator.newInstance();
使用场合
Java已经支持使用Class.newInstance()动态实例化类的实例。但是类必须拥有一个合适的构造器。有很多场景下不能使用这种方式实例化类,比如:
- 构造器需要参数
- 构造器有side effects
- 构造器会抛异常
因此,在类库中经常会有类必须拥有一个默认构造器的限制。Objenesis通过绕开对象实例构造器来克服这个限制。
典型应用
序列化,远程调用和持久化 -对象需要实例化并存储为到一个特殊的状态,而没有调用代码。
代理,AOP库和Mock对象 -类可以被子类继承而子类不用担心父类的构造器
容器框架 -对象可以以非标准的方式被动态实例化。
网友评论