Java实现通过反射获取指定类的所有信息

package com.ljy;

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

/**
 * 
 * @ClassName: TestClass
 * @Description: 通过反射获取指定类的所有信息
 * @author ljy
 * @date 2019年9月12日 上午11:29:02
 *
 */
public class TestClass {
    public static void main(String[] args) {
        try {
            Class clazz = Class.forName("com.ljy.Teacher"); // 需要查看类的路径
            
            System.out.println("---------类的成员变量---------");
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                System.out.println("属性名称:" + field.getName() + "    类型:" + field.getType());
            }

            System.out.println("---------类的成员方法---------");
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods) {
                System.out.println("方法名称:" + method.getName());
                System.out.println(method);
            }

            System.out.println("---------类的构造方法---------");
            @SuppressWarnings("rawtypes")
            Constructor[] constructors = clazz.getDeclaredConstructors();
            for (@SuppressWarnings("rawtypes")
            Constructor constructor : constructors) {
                System.out.println(constructor);
            }

            System.out.println("--------类所在包、完整名称、父类----------");
            System.out.println(clazz.getPackage());
            System.out.println(clazz);
            System.out.println(clazz.getSuperclass());

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}
 

 

posted @ 2019-09-12 11:34  我好高冷  阅读(528)  评论(0编辑  收藏  举报