package reflex;
import java.lang.reflect.Constructor;
/*
* 需求:通过反射,获取该构造方法的使用
* public Person(String name, int age, String address)
*
* Person p = new Person("mzy", 19, "XXX-xxx-x");
* sysout p
*/
public class ReflectDemo03_newInstance_have_parameter {
public static void main(String[] args) throws Exception {
// 获取字节码文件对象
Class c = Class.forName("reflex.Person");
// 获取带参数的构造器
Constructor con = c.getConstructor(String.class, int.class,
String.class);
// 通过带参构造方法对象,创建对象
Object obj = con.newInstance("mzy", 19, "XXX-xxx-x");
System.out.println(obj);
// 输出:Person [name=mzy, age=19, address=XXX-xxx-x]
}
}
其中的person:
package reflex;
public class Person {
// 成员变量
private String name;
int age;
public String address;
// 构造方法
public Person() {
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
private Person(String name) {
this.name = name;
}
public Person(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
// 成员方法
public void show() {
System.out.println("show");
}
public void method(String s) {
System.out.println("method" + s);
}
public String getString(String s, int i) {
return s + "---" + i;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", address=" + address + "]";
}
private void function() {
System.out.println("function");
}
}