为了正常的体验网站,请在浏览器设置里面开启Javascript功能!

java反射(java反射)

2017-09-26 14页 doc 38KB 137阅读

用户头像

is_769254

暂无简介

举报
java反射(java反射)java反射(java反射) java反射(java反射) java reflection (java反射) 来源: 网络转载 时间: 2009 - 6 / 15 java java reflection 是 程序开发语言的特征之一, 它允许运行中的 程序对自身进行检查, 或者说 "自审, 并能直接操作程序的内部属性.例如, 使用它能获得 java 类中各成员的名称并显示出来. 的这一能力在实际应用中也许用得不是很多 但是在其它的程序设计语言中根本就不存在这一特性.例如, java, c + + 中就没有办法在程序中...
java反射(java反射)
java反射(java反射) java反射(java反射) java reflection (java反射) 来源: 网络转载 时间: 2009 - 6 / 15 java java reflection 是 程序开发语言的特征之一, 它允许运行中的 程序对自身进行检查, 或者说 "自审, 并能直接操作程序的内部属性.例如, 使用它能获得 java 类中各成员的名称并显示出来. 的这一能力在实际应用中也许用得不是很多 但是在其它的程序语言中根本就不存在这一特性.例如, java, c + + 中就没有在程序中获得函数定义相关的信息 pascal、c 或者. javabean 是 reflection 的实际应用之一, 它能让一些工具可视化的操作软件组件.这些工具通过 reflection 动态的载入并取得 java 组件 (类) 的属性. 1. 一个简单的例子 考虑下面这个简单的例子, 让我们看看 reflection 是如何工作的. import java.lang.reflect. '; public class dumpmethods { public static void main (string [] args) { try { class c = class.forname (args [0]). method c.getdeclaredmethods () = (). for (int i = 0; i < m.length; i + +). system.out.println (m [i].tostring ()); } catch (throwable (e) system.err.println (e); } } } 按如下语句执行. java dumpmethods java.util.stack 它的结果输出为. the public java.lang.object java.util.stack.push (java.lang.object) public synchronized java.lang.object java.util.stack.pop () public synchronized java.lang.object java.util.stack.peek () java.util.stack.empty () public boolean public synchronized int java.util.stack.search (java.lang.object) 这样就列出了 java.util.stack 类的各名以及它们的限制符和返回类型. 这个程序使用 class.forname 载入指定的类, 然后调用 getdeclaredmethods 来获取这个类中定义了的方法列表. java.lang.reflect.methods 是用来描述某个类中单个方法的一个类. 2.开始使用. 用于 reflection 的类, 如 method, 可以在 java.lang.relfect 包中找到.使用这些类的时候必须要遵循三个步骤: 第一步是获得你想操作的类的 java.lang.class 对象.在运行中的 java 程序中, 用 java.lang.class 类来描述类和接口等. 下面就是获得一个 class 对象的方法之一. class c = class.forname (java.lang.string "); 这条语句得到一个 string 类的类对象.还有另一种方法, 如下面的语句. class c = int.class. 或者 class c = integer.type. 它们可获得基本类型的类信息.其中后一种方法中访问的是基本类型的封装类 (如 integer) 中预先定义好的 type 字段. 第二步是调用诸如 getdeclaredmethods 的方法, 以取得该类中定义的所有方法的列表. 一旦取得这个信息, 就可以进行第三步了 - 使用 reflection api 来操作这些信息, 如下面这段代码. class c = class.forname (java.lang.string "); method m [] =. getdeclaredmethods(); 系统。出来。println(M [ 0 ]。tostring()); 它将以文本方式打印出字符串中定义的第一个方法的原型。 在下面的例子中,这三个步骤将为使用反射处理特殊应用程序提供例证。 模拟是操作符 得到类信息之后,通常下一个步骤就是解决关于类对象的一些基本的问。例如,class.isinstance方法可以用于模拟是操作符: 类{ } 公开课请{ public static void main(String参数[ ]){ 尝试{ 类CLS =类forName(“”); 布尔B1 = CLS。isinstance(新的整数(37)); 系统,println(B1); 布尔B2 = CLS isinstance(新a()); 系统,println(B2); } catch(Throwable e){ 系统错误。println(E); } } } 在这个例子中创建了一个一类的类对象,然后检查一些对象是否是一 的实例。整数(37)不是,但新a()是。 3。找出类的方法 找出一个类中定义了些什么方法,这是一个非常有价值也非常基础的 用法下面的代码就实现了这一用法反射: 导入java。reflect *; 公共类:{ 私人诠释F1(对象p,x)抛出NullPointerException { 如果(p = NULL) 把新的nullpointerexception(); 返回x; } public static void main(String参数[ ]){ 尝试{ 类CLS =类forName(“方法”); 方法methlist [] = getdeclaredmethods() CLS; 为(int i = 0;i < methlist.length;i++){ 方法M = methlist [我]; 系统的输入(“name =“+ M. getname()); 系统的输入(“文类”+ M. getdeclaringclass()); 类[ ] = M getparametertypes() PVEC; 为(j = 0;J < pvec.length;j++) 系统的输入(“参数#”+ J +“”+ PVEC [J]); 类在[] = M getexceptiontypes(); 为(j = 0;J < evec.length;j++) 系统的输入(“EXC #”+ J +“”+在[ J ]); 系统的输入(“返回类型=“+ M. getreturntype()); 系统,println(“-----”); } } catch(Throwable e){ 系统错误。println(E); } } } 这个程序首先取得方法类的描述,然后调用getdeclaredmethods来 获取一系列的方法对象,它们分别描述了定义在类中的每一个方法, 包括公共方法、保护方法、包方法和私人方法等。如果你在程序中使 用getMethods来代替getdeclaredmethods,你还能获得继承来的各 个方法的信息。 After you get the list of Method objects, it's not difficult to display the parameter types, exception types, and return value types of these methods. These types are basic types or class types, which can be given in order by the object of the description class. 4. get constructor information The use of the class constructor is similar to the usage of the above access method, such as: Import java.lang.reflect.*; Public, class, constructor1 { Public, constructor1 () { } Protected constructor1 (int, I, double, d) { } Public, static, void, main (String, args[]) { {try Class CLS = Class.forName ("constructor1"); Constructor ctorlist[] = cls.getDeclaredConstructors (); For (int i = 0; I < ctorlist.length; i++) { Constructor CT = ctorlist[i]; System.out.println ('name =' + ct.getName ()); System.out.println ("decl class =" + ct.getDeclaringClass ()); Class pvec[] = ct.getParameterTypes (); For (int j = 0; J < pvec.length; j++) System.out.println ("param #" + j + "" + pvec[j]); Class evec[] = ct.getExceptionTypes (); For (int j = 0; J < evec.length; j++) System.out.println ("exc #" + j + "" + evec[j]); System.out.println ("-"); } } catch (Throwable, e) { System.err.println (E); } } } In this example, no information about the return type is obtained because the constructor does not return the type. 5. gets the field of the class (domain) It is also possible to find which data fields are defined in a class, and the following code is doing this: Import java.lang.reflect.*; Public, class, field1 { Private double d; Public, static, final, int, I = 37; String s = "testing""; Public, static, void, main (String, args[]) { {try Class CLS = Class.forName ("field1"); Field fieldlist[] = cls.getDeclaredFields (); For (int i = 0; I < fieldlist.length; i++) { Field FLD = fieldlist[i]; System.out.println ('name =' + fld.getName ()); System.out.println ("decl class =" + fld.getDeclaringClass ()); System.out.println ('type =' + fld.getType ()); Int mod = fld.getModifiers (); System.out.println ('modifiers =' + Modifier.toString (MOD)); System.out.println ("-"); } } catch (Throwable, e) { System.err.println (E); } } } This example is very similar to the previous one. A new object called Modifier is used in the example, and it is also a reflection class that describes the modifiers of the field members, such as private int". These modifiers themselves are described by integers, and Modifier.toString is used to return the string representation in the official order (such as "static" before "final"). And access methods, when you get the field, you can only get the field information (getDeclaredFields) declared in the current class, or you can also get the getFields defined in the parent class. 6. perform the method based on the name of the method The text here, the examples cited are all about how to get information about the class. We can also do some other things with reflection, such as executing a method that specifies the name. The following example demonstrates this operation: Import java.lang.reflect.*; Public, class, method2 { Public, int, add (int, a, int, b) { Return a + b; } Public, static, void, main (String, args[]) { {try Class CLS = Class.forName ("method2"); Class partypes[] = new Class[2]; Partypes[0] = Integer.TYPE; Partypes[1] = Integer.TYPE; Method meth = cls.getMethod ("add", partypes); Method2 methobj = new, method2 (); Object arglist[] = new Object[2]; Arglist[0] = new Integer (37); Arglist[1] = new Integer (47); Object retobj = meth.invoke (methobj, arglist); Integer retval = (Integer) retobj; System.out.println (retval.intvalue ()); } catch (Throwable, e) { System.err.println (E); } } } If a program in execution somewhere is aware of the need to perform in a certain way, the name of the method is specified when the program is running in (for example, JavaBean development environment will do such a thing), then the above program demonstrates how to do. In this example, getMethod is used to find a two integer parameters and a method named add. After you have found the method and created the corresponding Method object, execute it in the correct object instance. The implementation of this method, the need to provide a list of parameters, which are respectively packed integer two Integer 37 and 47 in the example above. The return of the execution method is the same as a Integer object, which encapsulates the return value of 84. 7. create new objects The constructor is not like that because the execution execution method, a constructor creates a new object (specifically, the process of creating a object includes memory allocation and object structure). So, the following above with the most similar example: Import java.lang.reflect.*; Public, class, constructor2 { Public, constructor2 () { } Public constructor2 (int, a, int, b) { System.out.println ("a =" + A +, "B =" + B); } Public, static, void, main (String, args[]) { {try Class CLS = Class.forName ("constructor2"); Class partypes[] = new Class[2]; Partypes[0] = Integer.TYPE; Partypes[1] = Integer.TYPE; Constructor CT = cls.getConstructor (partypes); Object arglist[] = new Object[2]; 阿格列斯[ 0 ] =新的整数(37); 阿格列斯[ 1 ] =新的整数(47); 对象retobj = CT newInstance(阿格列斯); } catch(Throwable e){ 系统错误。println(E); } } } 根据指定的参数类型找到相应的构造函数并执行它,以创建一个新的对象实例。使用这种方法可以在程序运行时动态地创建对象,而不是在编译的时候创建对象,这一点非常有价值。 8。改变字段(域)的值 的还有一个用处就是改变对象数据字段的值反射。反射可以从正在运行的程序中根据名称找到对象的字段并改变它,下面的例子可以说明这一点: 导入java。reflect *; 公共类专业{ 公共双D; public static void main(String参数[ ]){ 尝试{ 类CLS =类forName(“专业”); 场FLD = CLS GetField(“D”); 专业f2obj =新field2(); 系统的输入(“a”+ f2obj。D); FLD。setdouble(f2obj,12.34); 系统的输入(“a”+ f2obj。D); } catch(Throwable e){ 系统错误。println(E); } } } 这个例子中,字段D的值被变为了12.34。 9。使用数组 本文介绍的反射的最后一种用法是创建的操作数组。数组在java语 言中是一种特殊的类类型,一个数组的引用可以赋给引用观察下面的 例子看看数组是怎么工作的对象: 导入java。reflect *; 公共课2 { public static void main(String参数[ ]){ 尝试{ 类CLS =类。forName(“java。lang.string”); 对象数组arr = newInstance(CLS,10); 阵列。集(ARR,5,“这是一个测试”); string s =(字符串)阵列得到(ARR,5); 系统。了println(); } catch(Throwable e){ 系统错误。println(E); } } } 例中创建了10个单位长度的字符串数组,为第5个位置的字符串赋了值,最后将这个字符串从数组中取得并打印了出来。 下面这段代码提供了一个更复杂的例子: 导入java。reflect *; 公共类array2 { public static void main(String参数[ ]){ int变暗[ ] =新国际[ ] { 5, 10, 15 }; 对象数组arr = newInstance(integer.type,DIMS); 对象arrobj =阵列得到(ARR,3); 类= arrobj华彩。getclass()。getcomponenttype(); 系统,println(CLS); arrobj =阵列得到(arrobj,5); 阵列setint(arrobj,10, 37); 国际arrcast [ ] [ ] [ ] =(int [] [] [])ARR; 系统。出来。println(arrcast [ 3 ] [ 5 ] [ 10 ]); } } 例中创建了一个5 x 10 x 15的整型数组,并为处于[ 3 ] [ 5 ] [ 10 ] 的元素赋了值为注意37, A multidimensional array is actually an array of arrays. For example, after the first Array.get, arrobj is an array of 10 x 15. Then you get one of those elements, that is, an array of length 15, and use Array.setInt to assign the tenth elements of it. Notice that the type created when the array is dynamic does not know its type at compile time.
/
本文档为【java反射(java反射)】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。 本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。 网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。

历史搜索

    清空历史搜索