java 反射构造实例对象
**********************
构造对象实例
自java9开始,newInstance()方法不推荐使用,
@CallerSensitive
@Deprecated(since="9")
public T newInstance() throws InstantiationException, IllegalAccessException {
....
}
* clazz.newInstance()
* can be replaced by
* clazz.getDeclaredConstructor().newInstance()
可通过类的calss对象获得本类的构造函数,使用构造函数创建实例对象
**********************
示例
class Person{
private String name="瓜田李下";
private Integer age=24;
public Person() {
}
public Person(String name){
this.name=name;
}
public Person(Integer age){
this.age=age;
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return this.getName()+" "+this.getAge();
}
}
public class MyTest2 {
public static void main(String[] args){
Class<?> c=null;
try{
c=Class.forName("hello2.Person");
Person person=(Person) c.getDeclaredConstructor().newInstance();
System.out.println(person);
Constructor<?>[] con =c.getDeclaredConstructors();
for (Constructor<?> element:con){
System.out.println(element.toString());
}
Person person2=(Person) con[0].newInstance("瓜田李下2",23);
System.out.println(person2);
Person person3=(Person) con[1].newInstance(22);
System.out.println(person3);
Person person4=(Person) con[2].newInstance("瓜田李下4");
System.out.println(person4);
}catch (Exception e){
e.printStackTrace();
}
}
}
***********
控制台输出
瓜田李下 24
public hello2.Person(java.lang.String,java.lang.Integer)
public hello2.Person(java.lang.Integer)
public hello2.Person(java.lang.String)
public hello2.Person()
瓜田李下2 23
瓜田李下 22
瓜田李下4 24
说明:数组中构造函数的顺序与在类中定义的顺序无关