標籤:反射 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)