| Posted in JAVA技术 @ 2007/05/21 11:59 by 博爱老头
    Reflection 是 Java 程序开发语言的特征之一,它能突破本身的访问控制,允许运行中的 Java 程序进行“自审”,获得类的定义构造信息,并能直接操作程序的内部属性甚至改变初始值等等。而且这些特性是在其他的语言里面所没有的。利用这些,我们就可以进行oa的开发了。
  ok,首先还是先看一个最简单的例子。
列出 java.lang.Object 这个类的所有方法


输出结果为:
Mothod 0 is :public native int java.lang.Object.hashCode()
Mothod 1 is :public final native java.lang.Class java.lang.Object.getClass()
Mothod 2 is :protected void java.lang.Object.finalize() throws java.lang.Throwable
Mothod 3 is :protected native java.lang.Object java.lang.Object.clone() throws java.lang.CloneNotSupportedException
Mothod 4 is :public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
Mothod 5 is :public final void java.lang.Object.wait() throws java.lang.InterruptedException
Mothod 6 is :public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
Mothod 7 is :public boolean java.lang.Object.equals(java.lang.Object)
Mothod 8 is :public final native void java.lang.Object.notify()
Mothod 9 is :public final native void java.lang.Object.notifyAll()
Mothod 10 is :private static native void java.lang.Object.registerNatives()
Mothod 11 is :public java.lang.String java.lang.Object.toString()

常用的属性:
1、Field:字段信息,可以在程序运行的时候,用过setDouble,setInt等方法赋值。
2、Constructor:构造方法
3、Method:普通方法

常用的方法:
1、Class.forName("java.lang.Object");这个方法是获得java.lang.Object这个类的一个对象,我们可以把它赋值給Class,因为Class是所有类的超类。得到一个类的对象,我们还可以用ClassName.TYPE或者是ClassName.class。
2、ClassName.getDeclaredMethods() :获得ClassName类所有的定义方法。返回一个Method的数组。
3、ClassName.getDeclaredConstructors():获得ClassName类的构造器方法。返回一个Constructor的数组。
4、ClassName.getDeclaredFields():获得ClassName类的所有定义的字段。返回一个Field的数组。
5、Field.getModifiers():获得用来描述字段成员的访问控制符,如:private,public 等等。
6、Method.invoke(methobj, arglist):它的作用是通过Reflection 执行某个方法,返回Object对象。methobj是方法所在的类的一个实例,arglist是调用方法Method的参数列表。
下面是一个综合的例子:

输出结果是:

Mothod 0 is :public java.lang.String Test.getString(int,int)
Mothod 1 is :public void Test.doPrint()
Mothod 2 is :public void Test.method1()
Mothod 3 is :public void Test.method()
Mothod 4 is :public void Test.method3()
class Test's  Constructor 0 is :public Test(int)
class Test's  Constructor 1 is :public Test()
class Test's  Field 0 is :public int Test.aaa  Type is :int  Modifier is :public
class Test's  Field 1 is :private java.lang.String Test.bbb  Type is :class java.lang.String  Modifier is :private
Execute method getString() in Test returns:300


虽然在通常的开发中,不是很常用到Reflection,但是对于特殊的需求,来采用它的话,会得到意想不到的收获!

作者:博爱老头@博爱老头的草屋
地址:http://www.icnote.com/post/42/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!

文章来自: 本站原创
Tags:
发表评论
昵称
密码 [ 游客无需密码 ]
电邮
网址
打开HTML 打开UBB 打开表情 隐藏 记住我