彻底了解类的构成

本文介绍如何使用Java的运行时类型识别(RTTI)来深入探究类的内部结构,包括其方法和字段。通过两个实用工具类ShowMethods和ShowFields,可以方便地获取指定类的所有方法和字段,或按关键字搜索特定的方法和字段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

彻底了解类的构成
 
Java的RTTI(Run Time Type Identification)提供了很多手段,可以让程序员更好的了解类的构成,即类到底有哪些函数,有哪些成员,这对我们更好的理解类以及其他相关概念有很大的帮助.
 
这需要用类Class中有函数getMethods(),getDeclaredFields()来完成,在<Thinking in Java>中, Bruce Eckel写了个ShowMethods的工具类,”依葫芦画瓢”,我写了ShowFields类,这两个工具类就可以帮助我们来解剖任何一个类了,很有用吧!
 
No.1 ShowMethods.java
 
import java.lang.reflect.*;

public class ShowMethods {
  static final String usage =
    "usage: /n" +
    "ShowMethods qualified.class.name/n" +
    "To show all methods in class or: /n" +
    "ShowMethods qualified.class.name word/n" +
    "To search for methods involving 'word'";
  public static void main(String[] args) {
    if(args.length < 1) {
      System.out.println(usage);
      System.exit(0);
    }
    try {
      Class c = Class.forName(args[0]);
      Method[] m = c.getMethods();
      Constructor[] ctor = c.getConstructors();
      if(args.length == 1) {
        for (int i = 0; i < m.length; i++)
          System.out.println(m[i].toString());
        for (int i = 0; i < ctor.length; i++)
          System.out.println(ctor[i].toString());
      } 
      else {
        for (int i = 0; i < m.length; i++)
          if(m[i].toString()
             .indexOf(args[1])!= -1)
            System.out.println(m[i].toString());
        for (int i = 0; i < ctor.length; i++)
          if(ctor[i].toString()
             .indexOf(args[1])!= -1)
          System.out.println(ctor[i].toString());
      }
    } catch (ClassNotFoundException e) {
      System.out.println("No such class: " + e);
    }
  }
} ///:~
 
No.2 ShowFields.java
 
import java.lang.reflect.*;

public class ShowFields {
	
  static final String usage =
    "usage: /n" +
    "ShowFields qualified.class.name/n" +
    "To show all fields in class or: /n" +
    "ShowFields qualified.class.name word/n" +
    "To search for fields involving 'word'";
    
  public static void main(String[] args) {
    if(args.length < 1) {
      System.out.println(usage);
      System.exit(0);
    }
    try {
      Class c = Class.forName(args[0]);
      Field[] f = c.getDeclaredFields();
			
      if(args.length == 1) {
        for (int i = 0; i < f.length; i++)
          System.out.println(f[i].toString());
      } 
      else {
        for (int i = 0; i < f.length; i++)
          if(f[i].toString()
             .indexOf(args[1])!= -1)
            System.out.println(f[i].toString());
      }
    } catch (ClassNotFoundException e) {
      System.out.println("No such class: " + e);
    }
  }
} ///:~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值