先說下反射機制的概念:在運行狀態中,對於任意一個類,都能夠知道這個類的所有屬性和方法;對於任意一個對象,都能夠調用它的任意方法和屬性;這種動態獲取信息以及動態調用對象方法的功能稱為java語言的反射機制。
那么我們再來說下反射機制實現需要用到的類,總共有四大類:Class,Constructor,Method,Field。
其實實現反射需要如下幾個步驟:
1.獲取Class類
2.通過Class創建對象
3.獲取類中的方法
4.獲取類中的屬性,屬性值或類型
首先來說一下獲取Class的三種方法
public static void main(String[] args) { //第一種方式 通過對象獲取Class Student student = new Student(); Class sc=student.getClass(); }
public static void main(String[] args) { //第二種方式 直接通過類名獲取 Class sc2=Student.class; }
//第三種方式 通過類的全稱獲取(使用forName方法) Class sc3=Class.forName("com.java.Student"); //其實就是這個類所在的包的路徑
接下來通過Instance方法實例化對象
//使用newInstance方法來創建實例對象。 Student s1=(Student)sc.newInstance(); //這里需要強轉一下,因為創建出來的的對象是Object類型的
最后就是通過創建Field對象和Method對象來獲取屬性和方法(這里如果想要實現動態輸入必須要使set方法的setAccessible方法為true)
Field f1=s1.getClass().getDeclaredField("name"); //獲取方法中的name屬性 Method getm1=s1.getClass().getDeclaredMethod("getName", new Class[]{}); //獲取getname方法 這里的getName是可以修改成你想獲取的方法 Method setm1=s1.getClass().getDeclaredMethod("setName", new Class[]{f1.getType()});//這里的fi.getType是為了獲取setName輸入時的類型 setm1.setAccessible(true); //設置setm1是可訪問的 setm1.invoke(s1, "abc"); //通過setm1輸入值 System.out.println(getm1.invoke(s1, null)); //通過getm1獲取值
這段代碼是可以獲取到你所輸入的值,如果只是想要獲取屬性或方法的名字只需要前兩行!
上面介紹的是獲取單一屬性方法的辦法,
也可以獲取整個類的所有屬性和方法如下代碼所示:
Field []f = s1.getClass().getDeclaredFields();//獲取方法中所有的屬性 for(Field inputf :f){ //輸出所有的屬性 System.out.println(inputf); } Method[] allmethod = s1.getClass().getDeclaredMethods();//獲取類中所有的方法 for(Method inputm : allmethod){ //輸出所有的方法 System.out.println(inputm); }
這就是使用反射機制的具體步驟。
最后總結如下:
我們通過整體代碼可以知道,我們是可以通過用戶的輸入來調取某個類的某個方法或屬性,或是獲取某個類的所有方法或屬性,這也就對應了解到了開頭我們所說的反射的概念:動態獲取信息以及動態調用對象方法的功能稱為java語言的反射機制