1.通过已实例化对象获取Class(一)
Employee emp = new Employee();
Class<?> clazz = emp.getClass();
2.通过已实例化对象获取Class(二)
Employee emp = new Employee();
Class<?> clazz = emp.class;
3.通过包名+类名获取Class
Class<?> clazz = Class.forName("com.example.Employee");
4.通过类对象调用newInstance()方法获取Class
Class<?> clazz = Employee.class.newInstance();
5.通过类对象的getConstructor()或getDeclaredConstructor()方法获得构造器(Constructor)对象并调用其newInstance()方法创建对象
Class<?> clazz=Employee.class.getConstructor(Employee.class).newInstance();
ps:Employee类
package com.example;
public class Employee {
private Integer id;
private String gender;
private String name;
private String email;
public Employee() {
}
public Employee(Integer id, String gender, String name, String email) {
this.id = id;
this.gender = gender;
this.name = name;
this.email = email;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", gender='" + gender + '\'' +
", name='" + name + '\'' +
", email='" + email + '\'' +
'}';
}
}