您现在的位置: 无忧电子商务网 >> 信息学院 >> 程序开发 >> js >> 正文

Java Reflection (JAVA反射)

作者:作者:未…    信息学院来源:网络收集    点击数:    更新时间:2006-8-27 我要参与讨论

  > System.out.println("exc #" + j + " " + evec[j]);
System.out.println("-----");
}
} catch (Throwable e) {
System.err.println(e);
}
}
}

这个例子中没能获得返回类型的相关信息,那是因为构造器没有返回类型。

这个程序运行的结果是:

name = constructor1

decl class = class constructor1

-----

name = constructor1

decl class = class constructor1

param #0 int

param #1 double

-----

5.获取类的字段(域)

找出一个类中定义了哪些数据字段也是可能的,下面的代码就在干这个事情:


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

这个例子和前面那个例子非常相似。例中使用了一个新东西 Modifier,它也是一个 reflection 类,用来描述字段成员的修饰语,如“private int”。这些修饰语自身由整数描述,而且使用 Modifier.toString 来返回以“官方”顺序排列的字符串描述 (如“static”在“final”之前)。这个程序的输出是:

name = d

decl class = class field1

type = double

modifiers = private

-----

name = i

decl class = class field1

type = int

modifiers = public static final

-----

name = s

decl class = class field1

type = class java.lang.String

modifiers =

-----

和获取方法的情况一下,获取字段的时候也可以只取得在当前类中申明了的字段信息 (getDeclaredFields),或者也可以取得父类中定义的字段 (getFields) 。


6.根据方法的名称来执行方法

文本到这里,所举的例子无一例外都与如何获取类的信息有关。我们也可以用 reflection 来做一些其它的事情,比如执行一个指定了名称的方法。下面的示例演示了这一操作:

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(

上一页  [1] [2] [3] [4] [5] 下一页

在google里搜索更多Java Reflection (JAVA反射)

Google
Web www.51ec.org
【字体: 】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口
我来说两句 对此文章发表了评论
  昵 称: *必填    ·注册用户·
  评 分: 1分 2分 3分 4分 5分     严禁发表危害国家安全、政治、黄色淫秽等内容的评论,用户需对自己在使用本网站服务过程中的行为承担法律责任。本站管理员有权保留或删除评论内容,评论内容只代表机友个人观点,与本网站立场无关。  
评 论
内 容

 
评论列表 (最新 评论仅限网友观点!)

推荐文章
  • 此栏目下没有推荐信息学院
  • 供求信息




    | 设为首页 | 加入收藏 | 关于我们 | 广告服务 | 联系方式 | 友情链接 | 版权申明