了解完類加載機(jī)制之后,再來了解一下反射。
1.什么是反射
我們也許都知道怎么使用反射的api,那到底什么是反射。我的理解是,反射是一個java提供的一種機(jī)制,我們可以使用這種機(jī)制,在運行時,根據(jù)Class對象動態(tài)的獲取到它自身的構(gòu)造方法,成員變量和方法,并且也是以對象的形式拿到的,我們可以通過這些對象,動態(tài)的去修改變量或調(diào)用方法。這個Class對象是類加載過程中的加載時創(chuàng)建的。類加載過程和類加載機(jī)制
2.如何使用反射
這里只是說一下常用api的使用,反射的上限很高,比如動態(tài)代理,熱修復(fù)。一篇不可能說的完。
- 獲取一個java.lang.Class對象的三種方式。
try{
Student student = new Student();
Class<? extends Student> aClass = student.getClass();
Class<Student> studentClass = Student.class;
Class<?> aClass1 = Class.forName("com.xdw.myapplication.fanshe.Student");
}catch(Exception t){
}
第三種是最常用的。
- 獲取構(gòu)造方法
try{
// Student student = new Student();
// Class<? extends Student> aClass = student.getClass();
// Class<Student> studentClass = Student.class;
Class<?> studentClass = Class.forName("com.xdw.myapplication.fanshe.Student");
Constructor<?>[] constructors = studentClass.getConstructors();
System.out.println("-------------所有的公開的構(gòu)造方法--------------");
for(Constructor c:constructors){
System.out.println(c.getName());
}
System.out.println("-------------所有的構(gòu)造方法--------------");
Constructor<?>[] declaredConstructors = studentClass.getDeclaredConstructors();
for(Constructor c:declaredConstructors){
System.out.println(c.getName());
}
System.out.println("-------------根據(jù)入?yún)@得構(gòu)造方法--------------");
Constructor<?> constructor = studentClass.getDeclaredConstructor(boolean.class);
Constructor<?> constructor2 = studentClass.getDeclaredConstructor(int.class);
constructor2.setAccessible(true);
constructor2.newInstance(10);
System.out.print("con = "+constructor.getName());
}catch(Exception t){
}
- 獲取成員變量設(shè)置或調(diào)用方法。和構(gòu)造方法都差不多,只是入?yún)⒉煌K跃筒蝗珜懗鰜砹?。成員變量和方法可以根據(jù)變量名和方法名拿到。
Field[] fields = studentClass.getFields();
Field phoneNum = studentClass.getDeclaredField("phoneNum");
phoneNum.setAccessible(true);
phoneNum.set(student,"1888888888888");
Method str = studentClass.getMethod("showPhoneNum", String.class);
str.invoke(student,"aa");
public class Student {
public Student(String str){
System.out.println("(默認(rèn))的構(gòu)造方法 s = " + str);
}
//無參構(gòu)造方法
public Student(){
System.out.println("調(diào)用了公有、無參構(gòu)造方法執(zhí)行了。。。");
}
//有一個參數(shù)的構(gòu)造方法
public Student(char name){
System.out.println("姓名:" + name);
}
//有多個參數(shù)的構(gòu)造方法
public Student(String name ,int age){
System.out.println("姓名:"+name+"年齡:"+ age);//這的執(zhí)行效率有問題,以后解決。
}
//受保護(hù)的構(gòu)造方法
protected Student(boolean n){
System.out.println("受保護(hù)的構(gòu)造方法 n = " + n);
}
//私有構(gòu)造方法
private Student(int age){
System.out.println("私有的構(gòu)造方法 年齡:"+ age);
}
//**********字段*************//
public String name;
protected int age;
char sex;
private String phoneNum;
public void showPhoneNum(String str){
System.out.println(phoneNum);
}
}