Reflect 机制代码

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Reflect {

	// 获取属性信息
	public static void getFieldsInfo(Class c) {
		Field[] f = c.getDeclaredFields();
		for (int i = 0; i < f.length; i++) {
			System.out.println("\n属  性:\t" + f[i]);
			System.out.println("修饰符:\t"
					+ Modifier.toString(f[i].getModifiers()));
			System.out.println("类  型:\t" + f[i].getType());
			System.out.println("属性名:\t" + f[i].getName());
		}
	}

	// 获取方法信息
	public static void getMethodsInfo(Class c) {
		Method[] m = c.getDeclaredMethods();
		for (int i = 0; i < m.length; i++) {
			System.out.println("\n方  法:\t" + m[i].toString());

			System.out.println("修饰符:\t"
					+ Modifier.toString(m[i].getModifiers()));

			System.out.println("返回值:\t" + m[i].getReturnType());

			System.out.println("方法名:\t" + m[i].getName());

			System.out.print("参  数:\t");
			Class[] p = m[i].getParameterTypes();
			if (p.length == 0) {
				System.out.print("null");
			}
			for (int j = 0; j < p.length; j++) {
				System.out.print(p[j] + "\t");
			}
			System.out.println();

			System.out.print("异  常:\t");
			Class[] e = m[i].getExceptionTypes();
			if (e.length == 0) {
				System.out.print("null");
			}
			for (int j = 0; j < e.length; j++) {
				System.out.print(e[j] + "\t");
			}
			System.out.println();
		}
	}

	public static void main(String[] args) {
		Class c = String.class;
		// c = new Integer(5).getClass();
		// c = Class.forName(new Integer(5).getClass().getName());
		Reflect.getFieldsInfo(c);
		Reflect.getMethodsInfo(c);

	}
}

你可能感兴趣的:(java,C++,c,C#,J#)