我的java学习笔记(14)关于反射(part 3)

来源:互联网 发布:2017钓鱼网站源码 编辑:程序博客网 时间:2024/06/12 00:44

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();}}}}

输出结果



0 0
原创粉丝点击