下面以一个具体的实例来说明。此实例来自《精通Hibernate 3.0 Java数据库持久层开发实践》一书。
先在com.hqh.reflect下建一个文件UseInfojava
package com.hqh.reflect;
public class UseInfo {
private Integer id;
private String userName;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package com.hqh.reflect;
public class GetClassTest {
public static void main(String[] args) {
GetClassTest test = new GetClassTest();
if(test.ClassCheck())
System.out.println("OK");
}
public boolean ClassCheck() {
try {
System.out.println("通过类本身获得对象");
Class userClass = this.getClass();
System.out.println(userClass.getName());
System.out.println("===========");
System.out.println("通过子类的实例获得父类对象");
UseInfo useInfo = new UseInfo();
userClass = useInfo.getClass();
System.out.println(userClass.getName());
Class subUserClass = userClass.getSuperclass();
System.out.println(subUserClass.getName());
System.out.println("===========");
System.out.println("通过类名.class获取对象");
Class forClass = com.hqh.reflect.UseInfo.class;
System.out.println(forClass.getName());
System.out.println("===========");
System.out.println("通过类名的字符串获取对象");
Class forName = Class.forName("com.hqh.reflect.UseInfo");
System.out.println(forName.getName());
System.out.println("=============");
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
结果:
通过类本身获得对象
com.hqh.reflect.GetClassTest
===========
通过子类的实例获得父类对象
com.hqh.reflect.UseInfo
java.lang.Object
===========
通过类名.class获取对象
com.hqh.reflect.UseInfo
===========
通过类名的字符串获取对象
com.hqh.reflect.UseInfo
=============
OK