Java的反射机制(译自官方文档)

Using Java Reflection
By Glen McCluskey

January 1998

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

反射是Java语言的一种特性,它可以让Java程序在运行过程中检查、操作程序的内部属性。例如,它可以让一个Java类获取并显示其所有的成员变量名称。

The ability to examine and manipulate a Java class from within itself may not sound like very much, but in other programming languages this feature simply doesn't exist. For example, there is no way in a Pascal, C, or C++ program to obtain information about the functions defined within that program.

检查和操作一个Java类本身这种功能听起来似乎并不算什么,但其它语言并不具备这种特性,比如Pascal,C/C++,我们无法在这些语言写的程序中获取函数的定义。

One tangible use of reflection is in JavaBeans, where software components can be manipulated visually via a builder tool. The tool uses reflection to obtain the properties of Java components (classes) as they are dynamically loaded.

JavaBeans就是一个使用反射机制的例子,它使得构建工具可以非常直观的操作组件。构建工具使用反射获取Java组件(类的集合)的属性,并动态地加载它们。

A Simple Example

To see how reflection works, consider this simple example:

   import java.lang.reflect.*;
 
   public class DumpMethods {
      public static void main(String args[])
      {
         try {
            Class c = Class.forName(args[0]);
            Method m[] = c.getDeclaredMethods();
            for (int i = 0; i < m.length; i++)
                System.out.println(m[i].toString());
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

For an invocation of:

java DumpMethods java.util.Stack
the output is:

  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()
   public boolean java.util.Stack.empty()
   public synchronized 
     int java.util.Stack.search(java.lang.Object)

That is, the method names of class java.util.Stack are listed, along with their fully qualified parameter and return types.

以上,列出java.util.Stack类的方法名以及它的所有参数和返回类型。

This program loads the specified class using class.forName, and then calls getDeclaredMethods to retrieve the list of methods defined in the class. java.lang.reflect.Method is a class representing a single class method.

以上程序使用Class.forName方法加载指定的类,并调用getDeclaredMethods方法获取被加载类的方法列表。java.lang.reflect.Method是一个类,它表示某个类的方法。

Setting Up to Use Reflection

设置并使用反射功能

The reflection classes, such as Method, are found in java.lang.reflect. There are three steps that must be followed to use these classes. The first step is to obtain a java.lang.Class object for the class that you want to manipulate. java.lang.Class is used to represent classes and interfaces in a running Java program.

我们可以在java.lang.reflect包中找到反射的类,比如Method。使用这些类时必须遵循以下三个步骤。第一步,获取你想要操纵的类的java.lang.Class对象。java.lang.Class用于表示正在运行中的Java程序类或者接口。

One way of obtaining a Class object is to say:

   Class c = Class.forName("java.lang.String"); 

to get the Class object for String. Another approach is to use:

   Class c = int.class; 

or

  Class c = Integer.TYPE; 

to obtain Class information on fundamental types. The latter approach accesses the predefined TYPE field of the wrapper (such as Integer) for the fundamental type.
The second step is to call a method such as getDeclaredMethods, to get a list of all the methods declared by the class.

最后一种方法可以访问包装类型(例如Integer)的基本类型。
第二步,调用getDeclaredMethods之类的方法,以获取类的方法列表。

Once this information is in hand, then the third step is to use the reflection API to manipulate the information. For example, the sequence:

第三步,使用反射的API去操作这些信息,例如:

   Class c = Class.forName("java.lang.String"); 
   Method m[] = c.getDeclaredMethods();
   System.out.println(m[0].toString()); 

will display a textual representation of the first method declared in String.
In the examples below, the three steps are combined to present self contained illustrations of how to tackle specific applications using reflection.

将会显示String中声明的第一个方法,在往后的例子中,会使用这三个步骤并结合一些说明用以演示反射的使用。

Simulating the instanceof Operator

模拟实例化操作

Once Class information is in hand, often the next step is to ask basic questions about the Class object. For example, the Class.isInstance method can be used to simulate the instanceof operator:

获取到类的信息之后,下一步通常就是使用类的对象。例如,Class.isInstance方法可以用于模拟实例化操作:

class A {}

   public class instance1 {
      public static void main(String args[])
      {
         try {
            Class cls = Class.forName("A");
            boolean b1 = cls.isInstance(new Integer(37));
            System.out.println(b1);
            boolean b2 = cls.isInstance(new A());
            System.out.println(b2);
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

In this example, a Class object for A is created, and then class instance objects are checked to see whether they are instances of A. Integer(37) is not, but new A() is.
在这个例子中,创建一个A类型的对象,并检查实例化得到的对象是否属于A类,Integer(37)不是,new A()是。

Finding Out About Methods of a Class

找出类的方法

One of the most valuable and basic uses of reflection is to find out what methods are defined within a class. To do this the following code can be used:

反射功能经常被用于查找某个类中定义有什么样的方法。以下代码可以实现这样的功能:

   import java.lang.reflect.*;
   public class method1 {
      private int f1(
      Object p, int x) throws NullPointerException
      {
         if (p == null)
            throw new NullPointerException();
         return x;
      }
        
      public static void main(String args[])
      {
         try {
            Class cls = Class.forName("method1");
        
            Method methlist[] = cls.getDeclaredMethods();
            for (int i = 0; i < methlist.length;
               i++) {  
               Method m = methlist[i];
               System.out.println("name = " + m.getName());
               System.out.println("decl class = " + m.getDeclaringClass());
               Class pvec[] = m.getParameterTypes();
               for (int j = 0; j < pvec.length; j++)
                  System.out.println("param #" + j + " " + pvec[j]);
               Class evec[] = m.getExceptionTypes();
               for (int j = 0; j < evec.length; j++)
                  System.out.println("exc #" + j + " " + evec[j]);
               System.out.println("return type = " + m.getReturnType());
               System.out.println("-----");
            }
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

The program first gets the Class description for method1, and then calls getDeclaredMethods to retrieve a list of Method objects, one for each method defined in the class. These include public, protected, package, and private methods. If you use getMethods in the program instead of getDeclaredMethods, you can also obtain information for inherited methods.

上面这段程序首先获取method1类的描述,然后调用getDeclaredMethods方法获取其对象方法列表,这个列表涵盖了类所定义的所有方法,包括public、protected、private。如果使用getMethods方法代替getDeclaredMethods,你还可以获得该类从父类继承而来的方法。

Once a list of the Method objects has been obtained, it's simply a matter of displaying the information on parameter types, exception types, and the return type for each method. Each of these types, whether they are fundamental or class types, is in turn represented by a Class descriptor.

得到对象的方法列表后,接下来对于每个方法来说,它们要做的只是显示参数类型、异常类型、和返回类型而已。对于以上类型不管它们是基本类型还是一个类类型,它们都由类描述符表示。

The output of the program is:

   name = f1
   decl class = class method1
   param #0 class java.lang.Object
   param #1 int
   exc #0 class java.lang.NullPointerException
   return type = int
   -----
   name = main
   decl class = class method1
   param #0 class [Ljava.lang.String;
   return type = void
   -----

Obtaining Information About Constructors

获取构造器的相关信息

A similar approach is used to find out about the constructors of a class. For example:

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

There is no return-type information retrieved in this example, because constructors don't really have a true return type.
When this program is run, the output is:

在这个例子中我们并没有获得返回类型的信息,因为构造器没有真正的返回类型。
以下是上面这段程序运行的结果:

   name = constructor1
   decl class = class constructor1
   -----
   name = constructor1
   decl class = class constructor1
   param #0 int
   param #1 double
   -----

Finding Out About Class Fields

找出类的相关字段

It's also possible to find out which data fields are defined in a class. To do this, the following code can be used:

反射也可以用于查找类所定义的字段,以下代码实现了这样的功能:


   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 similar to the previous ones. One new feature is the use of Modifier. This is a reflection class that represents the modifiers found on a field member, for example "private int". The modifiers themselves are represented by an integer, and Modifier.toString is used to return a string representation in the "official" declaration order (such as "static" before "final").

这个列子和上一个类似。Modifier是其中的一个新功能,它是一个反射类,表示字段的修饰符,例如"private int"。修饰符本身表示整型,Modifier.toString方法则用于返回修饰符的字符串。

The output of the program is:

  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 =
   ----- 

As with methods, it's possible to obtain information about just the fields declared in a class (getDeclaredFields), or to also get information about fields defined in superclasses (getFields).

与方法一样,我们可以用getDeclaredFields仅获取该类所声明的字段,也可以用getFields获取继承字段。

Invoking Methods by Name

使用类名调用方法

So far the examples that have been presented all relate to obtaining class information. But it's also possible to use reflection in other ways, for example to invoke a method of a specified name.

到目前为止我们已经给出了所有使用反射获取对象相关信息的例子。但反射还有别的用途,例如使用指定名称调用类的方法。

To see how this works, consider the following example:


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

Suppose that a program wants to invoke the add method, but doesn't know this until execution time. That is, the name of the method is specified during execution (this might be done by a JavaBeans development environment, for example). The above program shows a way of doing this.

以上程序列举了invoke的用法,假设一个程序想在运行过程中需要调用一个它所不知道的"add"方法,且方法的名字可以在执行进行时指定(实际使用中把硬编码"add"替换为字符串变量就可以了)。

getMethod is used to find a method in the class that has two integer parameter types and that has the appropriate name. Once this method has been found and captured into a Method object, it is invoked upon an object instance of the appropriate type. To invoke a method, a parameter list must be constructed, with the fundamental integer values 37 and 47 wrapped in Integer objects. The return value (84) is also wrapped in an Integer object.

getMethod方法用于获取以两个整型为参数并且有指定名称的方法。一旦这个方法被找到并装载到Method对象里,它便可以调用对应类型的实例对象。而为了调用方才被找到的这个方法,我们还需要给它提供两个整型(37和47)包装类对象作为参数,返回值(84)也是整型包装类。

Creating New Objects

创建新的对象

There is no equivalent to method invocation for constructors, because invoking a constructor is equivalent to creating a new object (to be the most precise, creating a new object involves both memory allocation and object construction). So the nearest equivalent to the previous example is to say:

在java语言中没有哪种方法可以起到和构造器相类似的作用,因为调用一个构造器相当于创建一个新的对象(准确的说,创建一个新对象涉及内存分配和对象构造)。

   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];
            arglist[0] = new Integer(37);
            arglist[1] = new Integer(47);
            Object retobj = ct.newInstance(arglist);
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   } 

which finds a constructor that handles the specified parameter types and invokes it, to create a new instance of the object. The value of this approach is that it's purely dynamic, with constructor lookup and invocation at execution time, rather than at compilation time.

上面的例子调用构造器并使用指定参数类型创建实例对象。这种做法的好处是,它是纯动态的,可以在运行阶段调用,而非编译阶段。

Changing Values of Fields

修改字段的值

Another use of reflection is to change the values of data fields in objects. The value of this is again derived from the dynamic nature of reflection, where a field can be looked up by name in an executing program and then have its value changed. This is illustrated by the following example:

反射还可以用于修改对象字段的值(待译)

   import java.lang.reflect.*;
        
   public class field2 {
      public double d;
        
      public static void main(String args[])
      {
         try {
            Class cls = Class.forName("field2");
            Field fld = cls.getField("d");
            field2 f2obj = new field2();
            System.out.println("d = " + f2obj.d);
            fld.setDouble(f2obj, 12.34);
            System.out.println("d = " + f2obj.d);
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   } 

In this example, the d field has its value set to 12.34.

Using Arrays

使用数组

One final use of reflection is in creating and manipulating arrays. Arrays in the Java language are a specialized type of class, and an array reference can be assigned to an Object reference.

反射的最后一种用途是用于创建并操作数组,在 Java 语言中数组是一种特殊的类,并且数组引用可以分配给一个对象的引用。

To see how arrays work, consider the following example:

   import java.lang.reflect.*;
        
   public class array1 {
      public static void main(String args[])
      {
         try {
            Class cls = Class.forName("java.lang.String");
            Object arr = Array.newInstance(cls, 10);
            Array.set(arr, 5, "this is a test");
            String s = (String)Array.get(arr, 5);
            System.out.println(s);
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

This example creates a 10-long array of Strings, and then sets location 5 in the array to a string value. The value is retrieved and displayed.
A more complex manipulation of arrays is illustrated by the following code:

   import java.lang.reflect.*;
        
   public class array2 {
      public static void main(String args[])
      {
         int dims[] = new int[]{5, 10, 15};
         Object arr = Array.newInstance(Integer.TYPE, dims);
        
         Object arrobj = Array.get(arr, 3);
         Class cls = arrobj.getClass().getComponentType();
         System.out.println(cls);
         arrobj = Array.get(arrobj, 5);
         Array.setInt(arrobj, 10, 37);
        
         int arrcast[][][] = (int[][][])arr;
         System.out.println(arrcast[3][5][10]);
      }
   }

This example creates a 5 x 10 x 15 array of ints, and then proceeds to set location [3][5][10] in the array to the value 37. Note here that a multi-dimensional array is actually an array of arrays, so that, for example, after the first Array.get, the result in arrobj is a 10 x 15 array. This is peeled back once again to obtain a 15-long array, and the 10th slot in that array is set using Array.setInt.

以上例子中创建了一个5x10x15大小的整型数组,并且将[3][5][10]这个位置的值设为37。注意,这里是一个多维数组,因此,在第一次使用Array.get方法之后,arrobj将变为一个10x15的多维数组,之后我们又再次将数组降维,得到一个长度为15的数组,并使用Array.setInt设置第10个位置的值。

Note that the type of array that is created is dynamic, and does not have to be known at compile time.

你可能感兴趣的:(Java的反射机制(译自官方文档))