ITEEDU

获取类的方法信息

  1. 获取方法名
  2. 获取方法参数信息
import java.lang.reflect.*;
public class method1 {
	private int f1(Object p, int x) throws NullPointerException {
		if (p == null)
		throw new NullPointerException();
		return x;
	}
	public static void main(String args[]) {
		try {
			Class cls = Class.forName("method1");
			Method methlist[] = cls.getDeclaredMethods();
			for (int i = 0; i < methlist.length; i++) {
				Method m = methlist[i];
				System.out.println("name = " + m.getName());
				System.out.println("decl class = " + m.getDeclaringClass());
				Class pvec[] = m.getParameterTypes();
				for (int j = 0; j < pvec.length; j++)
						System.out.println("param #" + j + " " + pvec[j]);
				Class evec[] = m.getExceptionTypes();
				for (int j = 0; j < evec.length; j++)
						System.out.println("ExceptionType #" + j + " " + evec[j]);
				System.out.println("return type = " + m.getReturnType());
				System.out.println("-----");
			}
		} catch (Throwable e) {
			System.err.println(e);
		}
	}
}