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);
}
}
} ///:~