关于JAVA中Constructor的使用

127 阅读1分钟
@Test
public void test3() throws Exception {
    Class<Employee> employeeClass = Employee.class;
    Constructor<Employee> constructor = employeeClass.getConstructor();
    Employee employee1 = constructor.newInstance();
    employee1.setName("lisi");
    System.out.println(employee1.toString());

    Constructor<Employee> constructor2 = employeeClass.getConstructor(String.class);
    Employee wangwu = constructor2.newInstance("wangwu");
    System.out.println(wangwu.toString());
}

public class Employee {

private String name;
private double salary;
private Date hireDay;

public Employee() {

}

public Employee(String name) {
    this.name = name;
}

public Employee(String name, double salary) {
    this.name = name;
    this.salary = salary;
}

public Employee(String name, double salary, Date hireDay) {
    this.name = name;
    this.salary = salary;
    this.hireDay = hireDay;
}

@Override
public int hashCode() {
    return Objects.hash(name,salary,hireDay);
}



@Override
public String toString() {
    return getClass().getName() +
            "{ name='" + name + ''' +
            ", salary=" + salary +
            ", hireDay=" + hireDay +
            '}';
}

@Override
public boolean equals(Object obj) {
    if(null==obj){
        return false;
    }
    if(this==null){
        return false;
    }
    if(obj.getClass()!=getClass()){
        return false;
    }
    Employee other = (Employee) obj;
    return Objects.equals(name,other.name)
            &&salary==other.salary
            && Objects.equals(hireDay,other.hireDay);
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public double getSalary() {
    return salary;
}

public void setSalary(double salary) {
    this.salary = salary;
}

public Date getHireDay() {
    return hireDay;
}

public void setHireDay(Date hireDay) {
    this.hireDay = hireDay;
}