package cn.itcast.jdbc;
import java.lang.reflect.Constructor;
import cn.itcast.domain.User;
public class ReflectTest {
public static void main(String[] args) throws Exception {
User user=(User)create(User.class);
System.out.println(user);
}
//给定一个类,构造出一个对象。
static Object create(Class clazz) throws Exception{
Constructor con = clazz.getConstructor(String.class); //找到构造器
Object obj=con.newInstance("test name"); //构造出对象
return obj;
}
}
使用反射代码可读性很差,但是会很灵活
User.java
package cn.itcast.domain;
import java.util.Date;
public class User {
private int id;
private String name;
private Date birthday;
private float money;
public User() {
}
public User(String name) {
this.name = name;
}
public User(float money) {
this.money = money;
}
@Override
public String toString() {
return "id=" + this.id + " name=" + this.name + " birthday="
+ this.birthday + " money=" + this.money;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public float getMoney() {
return money;
}
public void setMoney(float money) {
this.money = money;
}
}