我的java學習筆記(14)關於反射(part 3)

來源:互聯網
上載者:User

標籤:反射   java   異常   eclipse   

1.java.lang.reflect包中的Array類允許動態地建立數組。

2.在調用Array類中的靜態方法newInstance是需要提供兩個參數,一個是數組的元素類型,一個是數組的長度。

3.Class類的getComponentType方法可以確定數組對應的類型。

4.整型數群組類型int[]可以被轉換成Object,但不能轉換成對象數組。


相關的執行個體代碼

import java.lang.reflect.*;import java.util.*;public class test{public static void main(String[] args){int[] a = {1,2,3};a = (int[])goodCopyOf(a,10);System.out.println(Arrays.toString(a));String[] b = {"one","two","three"};b = (String[]) goodCopyOf(b,10);System.out.println(Arrays.toString(b));System.out.println("下面這個方法將產生一個異常:");b = (String[])badCopyOf(b,10);}public static Object[] badCopyOf(Object[] a,int newLength){Object[] newArray = new Object[newLength];System.arraycopy(a, 0, newArray, 0, Math.min(a.length, newLength));return newArray;}public static Object goodCopyOf(Object a,int newLength){Class c1 = a.getClass();if(!c1.isArray())return null;Class componentType = c1.getComponentType();int length = Array.getLength(a);Object newArray = Array.newInstance(componentType,newLength);System.arraycopy(a,0,newArray,0,Math.min(length, newLength));return newArray;}}

輸出結果



5.Method類中的invoke方法可以調用封裝在當前Method對象中的方法。

6.如果返回值是基本類型,invoke方法會返回其封裝器類型。


相關的執行個體代碼

import java.lang.reflect.*;public class test {public static void main(String[] args) throws Exception{Method squ = test.class.getMethod("square", double.class);Method sqr = Math.class.getMethod("sqrt",double.class);printTable(1,10,10,squ);printTable(1,10,10,sqr);}public static double square(double x){return x*x;}public static void printTable(double begin,double end,int n,Method f){double dx = (end - begin)/(n - 1);for(double x = begin; x <= end;x += dx){try{double y =(Double) f.invoke(null, x);System.out.printf("%10.4f | %10.4f%n" , x, y);}catch(Exception e){e.printStackTrace();}}}}

輸出結果



我的java學習筆記(14)關於反射(part 3)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.