• 细说反射API


    有时候需要知道比Class类所提供的信息多得多的有关一个类型的信息。出于这种目的,可以使用程序包java.lang.reflect中的类,换句话说就是所说的反射API。这个类集提高了Class类的能力和有效性。

    反射API支持一种名为自省的行为,这种行为实际上使一个类描述自身。

    反射API使对象具有反射自己和发现自身内容的能力。程序包java.lang.reflect定义了很多类,这些类总体上对一个对象作了完整的描述。

    下面给出了这3种类表示类的构建块:
    (1)Constructor类的每个实例都提供了关于一个类的一个构造函数的信息,并且为调用程序提供了使用这个构造函数以创建一个对象的方式。
    (2)Method类的每个实例都提供了关于一个类的一种方法的信息,并且为调用程序提供了调用这种方法的方式。这种方法可能是类的方法或者实例的方法,而且可能是抽象的。
    (3)Field类的每个实例都提供了关于一个类的一个域的信息,并且为调用程序提供了获得和设置这个域的值的方法。这个域可以是类变量或者实例变量。

    下面用一个例子帮助大家了解:

      
      1import java.lang.reflect.*;
      2
      3public class ReflectionDemo
      4{
      5    public static void main(String[] args)
      6    {
      7        try
      8        {
      9            ReflectionDemo demo = new ReflectionDemo();
     10
     11            Method myMethod;
     12            Class[] parameterTypes;
     13            Object[] parameters;
     14            Object result;
     15
     16            TestClass testObj = new TestClass();
     17            Class myClass = testObj.getClass();
     18
     19            System.out.println("Methods defined in class " + myClass.getName());
     20            demo.printMethods(myClass);
     21            System.out.println();
     22
     23            //input parameter types for method
     24            parameterTypes = new Class[]{int.class, String.class};
     25
     26            //input parameter for method
     27            parameters = new Object[] {new Integer(2), "this is test"};
     28
     29            //get method by name and parameter types
     30            myMethod = myClass.getMethod("test1", parameterTypes);
     31
     32            //run it
     33            System.out.println(myMethod.getName());
     34            result = demo.execute(testObj, myMethod, parameters);
     35            System.out.println("Returned value: " + result);
     36
     37            //input parameter types for method
     38            parameterTypes = new Class[] {int[].class};
     39
     40            //input parameters for method
     41            int[] nums = {12345};
     42            parameters = new Object[] {nums};
     43
     44            //get method by name parameter types
     45            myMethod = myClass.getMethod("test2", parameterTypes);
     46
     47            //run it
     48            System.out.println(myMethod.getName());
     49            result = demo.execute(testObj, myMethod, parameters);
     50            System.out.println("Result value: " + result);
     51
     52            //input parameter types for method
     53            parameterTypes = new Class[] {};
     54
     55            //input parameters for method
     56            parameters = new Object[] {};
     57            myMethod = myClass.getMethod("test3", parameterTypes);
     58
     59            //run it
     60            System.out.println(myMethod.getName());
     61            result = demo.execute(testObj, myMethod, parameters);
     62            System.out.println("Returned value: " + result);
     63        }

     64        catch(Exception e)
     65        {
     66            System.out.println(e);
     67        }

     68    }

     69
     70    //print out definition of declared methods
     71    public void printMethods(Class aClass)
     72    {
     73        Method[] ms = aClass.getDeclaredMethods();
     74        for(int i = 0; i < ms.length; i ++)
     75        {
     76            System.out.println(ms[i].toString());
     77        }

     78    }

     79
     80    //execute method of an object with given parameters
     81    public Object execute(Object classObject, Method myMethod, Object[] parameters) throws Exception
     82    {
     83        String errorMsg;
     84
     85        try
     86        {
     87            //run the method
     88            return myMethod.invoke(classObject, parameters);
     89        }

     90        catch(InvocationTargetException invokeE)
     91        {
     92            //catch exception thrown by the invoked method
     93            errorMsg = invokeE.getTargetException().getMessage();
     94        }

     95
     96        throw new Exception(errorMsg);
     97
     98    }

     99}

    100
    101class TestClass
    102{
    103    public void test1(int i, String str)
    104    {
    105        System.out.println("1 = " + i + " and " + "str = \"" + str + "\"");
    106    }

    107
    108    public int test2(int[] nums)
    109    {
    110        int sum = 0;
    111        for(int i = 0; i < nums.length; i ++)
    112            sum += nums[i];
    113
    114        return sum;
    115    }

    116
    117    public String test3()
    118    {
    119        return "\"No input parameter\"";
    120    }

    121}

    122
    123
    124


    结果如下:
    Methods defined in class TestClass
    public void TestClass.test1(int,java.lang.String)
    public int TestClass.test2(int[])
    public java.lang.String TestClass.test3()

    test1
    1 = 2 and str = "this is test"
    Returned value: null
    test2
    Result value: 15
    test3
    Returned value: "No input parameter"

  • 相关阅读:
    RHEL7使用ssm命令管理LVM
    LVM命令摘要
    Linux用户磁盘配额
    Linux磁盘分区实战案例
    通过yum升级CentOS/RHEL最小化安装
    RHEL7下PXE+FTP+Kickstart无人值守安装操作系统
    配置VSFTP服务器
    RHEL7下PXE+NFS+Kickstart无人值守安装操作系统
    RHEL7下PXE+Apache+Kickstart无人值守安装操作系统
    html5实现图片自适应手机屏幕页面的css
  • 原文地址:https://www.cnblogs.com/bankey/p/357853.html
Copyright © 2020-2023  润新知