Java代码 package reflect;( u L& _' w8 U1 Y# M
import java.lang.reflect.*;0 E* ]! ~1 y% r8 G
public class DumpMethods {
% l/ g$ _ m8 P! p0 Q) S0 h. M1 }5 n private double d;
+ |: l3 n0 h. j1 J# G) v0 d/ \ public static final int i = 37;- l1 |' J; B- R) L5 P& ]3 w
String s = "testing"; y6 E. v+ d, T: P
public DumpMethods() {& R% m5 B4 V5 Y0 F
}
% ~' R6 D! \/ P7 W3 ~; h3 b9 x, y, L* X protected DumpMethods(int i, double d) {
2 V; j8 f6 h' C% I' [1 }: S }
8 C+ ]4 [# _8 `1 W ?% G public int add(int a, int b) {
5 q% c; n2 ^; w$ W1 l, d; g+ l return a + b;: V! ~, y+ ^! u/ u9 L
}# G) V! i' W& j
public static void main(String args[]) {
, \6 C$ } @: S' G, h5 p try {
; v5 {2 Z7 I4 p+ _& S! F/ U, B Class c = Class.forName("java.lang.String");: ]8 {4 ]3 q8 ]0 R* `6 d
// 得到指定类java.lang.String拥有的方法,将它们分别列出来。6 O# A0 Y( _! Z/ B6 z* H" y
Method m[] = c.getDeclaredMethods();& E# T3 M- j* |; E
for (int i = 0; i < m.length; i++) {
, o' g! _3 P, z" a Method mthod = m;
! x6 i- f% k8 Z8 |: Q System.out.println(mthod.getName());// 打印方法名
5 r: V5 C _, w; t' H: d System.out.println(mthod.getDeclaringClass());// 打印方法名
, S/ g' H7 d, _! S- I( @ // ...得到参数类型5 N! i3 Z6 L/ M/ ?: C
Class pvec[] = mthod.getParameterTypes();$ o; I+ H; p% m9 d3 ^: D
for (int j = 0; j < pvec.length; j++)* `3 o, N0 b% t0 D0 U
System.out.println("param #" + j + " " + pvec[j]);
' w4 G8 D3 y+ z! } // ...得到异常类型& L: o* ?" C' p. c8 v( [: [3 _: N
Class evec[] = mthod.getExceptionTypes();
: |( l: ]6 [% T! i! ` for (int j = 0; j < evec.length; j++)1 F# V& F# ^, l) E
System.out.println("exc #" + j + " " + evec[j]);
/ l) x& C1 q0 [1 G5 b, w% t" T* y // ...得到返回类型5 V! A9 e- V `; m
System.out.println("return type = " + mthod.getReturnType());
% W$ P- U0 e- g- A( l6 x8 D' r2 Z System.out.println("-----");
! K4 z9 P$ p: P: t+ H/ |! ]; l) B) z // ...System.out.println(m.toString());//打印方法名6 U2 m# Z- a2 t5 m* G: L( Z* q
: d! f4 r7 {7 N, e( `( u
} |