获取Class对象的三种方式
通过getClass()方法;
通过.class静态属性;
通过Class类中的静态方法forName();
创建Users类
public class Users {
private String username;
private int userage;
public String getUsername(){
return username;
}
public void setUsername(String username){
this.username = username;
}
public int getUserage(){
return userage;
}
public void setUserage(int userage){
this.userage = userage;
}
}
通过getClass()方法获取Class对象
/**
* 通过getClass()方法获取该类的Class对象
*/
public class GetClass1 {
public static void main(String[] args){
Users users = new Users();
Users users1 = new Users();
Class clazz = users.getClass();
System.out.println(clazz);
System.out.println(clazz.getName());
System.out.println(clazz.getClass() == users1.getClass());
}
}
通过.class静态属性获取Class对象
/**
* .class静态属性获取Class对象
*/
public class GetClass2 {
public static void main(String[] args){
Class clazz = Users.class;
Class clazz2 = Users.class;
System.out.println(clazz);
System.out.println(clazz.getName());
System.out.println(clazz == clazz2);
}
}
通过forName()获取Class对象
/**
* 通过Class.forName("class Name")获取Class对象
*/
public class GetClass3 {
public static void main(String[] args) throws Exception{
Class clazz = Class.foeName("com.test.Users");
Class clazz2 = Class.foeName("com.test.Users");
System.out.println(clazz);
System.out.println(clazz.getName());
System.out.println(clazz == clazz2);
}
}