码迷,mamicode.com
首页 > 编程语言 > 详细

Java反射应用

时间:2019-01-02 19:08:25      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:style   str   构造   dna   ++   public   system   out   struct   

public static void main(String[] args) {
        Integer i = 0;
        printClassMessage(i);
    }
    private static void printClassMessage(Object obj) {
        Class c = obj.getClass();
        System.out.println("类的名字是:");
        System.out.println(c.getName());
        
        //成员变量
        System.out.println("------------------------");
        System.out.println("类的成员变量是:");
        Field[] fs = c.getDeclaredFields();
        for(Field f: fs) {
            Class fieldType = f.getType();
            String typeName = fieldType.getName();
            String fieldName = f.getName();
            System.out.println(typeName+" "+fieldName);
        }

        //构造函数
        System.out.println("------------------------");
        System.out.println("类的构造函数是:");
        Constructor[] cts = c.getDeclaredConstructors();
        for(Constructor ct : cts) {
            String value = "";
            value += ct.getName() + "(";
            Class[] paramTypes = ct.getParameterTypes();
            for(Class param: paramTypes) {
                value += param.getName() + ",";
            }
            if (value.endsWith(",")) {
                value = value.substring(0,value.length()-1);
            }
            value += ")";
            System.out.println(value);
        }    
                
        //内部方法
        System.out.println("------------------------");
        Method[] ms = c.getMethods();
        System.out.println("类的内部方法是:");
        for(int i=0;i<ms.length;i++) {
            String value = "";
            Class returnType = ms[i].getReturnType();
            value += returnType.getName() + " ";
            value += ms[i].getName() + "(";
            Class[] paraTypes = ms[i].getParameterTypes();
            for(Class c1 : paraTypes) {
                value += c1.getName() + ",";
            }
            if (value.endsWith(",")) {
                value = value.substring(0,value.length()-1);
            }
            value += ")";
            System.out.println(value);
        }
    }

 

Java反射应用

标签:style   str   构造   dna   ++   public   system   out   struct   

原文地址:https://www.cnblogs.com/liw66/p/10209678.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!