java可以通過反射機制獲取類的各種信息和創建類的實例,就算將構造方法用private修飾,也可以創建,通過反射能創建很多強大的功能,算是寫框架的常用方法和技巧
這裏只介紹通過反射獲取類的各種信息
實驗類
package learn.reflect;
public class UserBean {
private Integer id;
private String usrname;
private String phone;
public UserBean(Integer id, String usrname, String phone) {
super();
this.id = id;
this.usrname = usrname;
this.phone = phone;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsrname() {
return usrname;
}
public void setUsrname(String usrname) {
this.usrname = usrname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
啓動類
package learn.reflect;
public class Main {
public static void main(String[] args) {
Class u = null;
try {
// 運行時加載以編譯好的xxx.class文件,默認路徑在classPath
u = Class.forName("learn.reflect.UserBean");
System.out.println("找到xxx.class文件");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 獲取class後,能獲取該類的一切信息進行判斷或查看,有很多getxxx方法和isxxx方法
System.out.println("class文件和包路徑: " + u.getName());
System.out.println(u.getComponentType());
System.out.println(u.getCanonicalName());
System.out.println(u.getModifiers());
System.out.println(u.getSimpleName());
System.out.println(u.getTypeName());
System.out.println(u.getAnnotatedInterfaces());
System.out.println(u.getAnnotatedSuperclass());
System.out.println(u.getAnnotations());
System.out.println(u.getConstructors());
System.out.println(u.getDeclaredAnnotations());
System.out.println(u.getFields());
System.out.println(u.getMethods());
System.out.println();
u.getMethods();
}
}