zoukankan      html  css  js  c++  java
  • Java反射学习1

    Java反射学习

    Reflection是Java 程序开发语言的特征之一,它允许运行中的 Java 程序对自身进行检查,或者说"自审",并能直接操作程序的内部属性。例如,使用它能获得 Java 类中各成员的名称并显示出来。

    Java 的这一能力在实际应用中也许用得不是很多,但是在其它的程序设计语言中根本就不存在这一特性。例如,Pascal、C 或者 C++ 中就没有办法在程序中获得函数定义相关的信息。

    JavaBean 是 reflection 的实际应用之一,它能让一些工具可视化的操作软件组件。这些工具通过 reflection 动态的载入并取得 Java 组件(类) 的属性。

    反射除了显示类的自身信息外,它还可以创建对象和执行方法等

    (1)找出类的方法
      找出一个类中定义了些什么方法,这是一个非常有价值也非常基础的 reflection 用法,示例代码如下:

    http://iwtxokhtd.javaeye.com/blog/359584


    import java.lang.reflect.*; /** *通过反射执行类的方法 */ class PerformMethod { //声明一个简单的方法,用于测试 public int add(int a,int b){ return a+b; } public static void main(String[] args)throws Exception { //获取本类的类对象 Class c=Class.forName("PerformMethod"); /** *声明add方法参数类型的集合 *共有两个参数,都为Integer.TYPE */ Class []paramTypes=new Class[2]; paramTypes[0]=Integer.TYPE; paramTypes[1]=Integer.TYPE; //根据方法名和参数类型集合得到方法 Method method=c.getMethod("add",paramTypes); //声明类的实例 PerformMethod pm=new PerformMethod(); //传入参数的集合 Object []argList=new Object[2]; //传入37和43 argList[0]=new Integer(37); argList[1]=new Integer(43); //执行后的返回值 Object returnObj=method.invoke(pm,argList); //类型转换下 Integer returnVal=(Integer)returnObj; //打印结果 System.out.println("方法执行结果为:"+returnVal.intValue()); } }

  • 相关阅读:
    CSS
    Html5
    [LeetCode] 78. Subsets(子集)
    [LeetCode] 22. Generate Parentheses(括号生成器)
    [LeetCode] 406. Queue Reconstruction by Height(按身高重排队列)
    [LeetCode] 46. Permutations(全排列)
    [LeetCode] 94. Binary Tree Inorder Traversal(二叉树的中序遍历)
    [LeetCode] 338. Counting Bits(数比特位)
    [LeetCode] 763. Partition Labels(标签划分)
    [LeetCode] 20. Valid Parentheses(有效的括号)
  • 原文地址:https://www.cnblogs.com/danghuijian/p/4400648.html
Copyright © 2011-2022 走看看