反射类字段

package com.rlt.robam.reflect;


import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Created by as on 2017-04-12.
 */
public class ReflectTest1 {
    //http://blog.csdn.net/zhangquanit/article/details/52925619
    private static String name;

    public static void main(String[] args) {
        //扫描器 获取键盘输入信息
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            name = scanner.next();
            System.out.println("获取已输入全限定类名:" + name);
            break;
        }
        //反射类
        Class aClass = null;
        try {
            aClass = Class.forName(name);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return;
        }
        reflectClass(aClass);
    }

    private static void reflectClass(Class aClass) {
        //getName()返回的是虚拟机里面的class的表示
        //getCanonicalName()返回的是更容易理解的表示
        //getSimpleName()返回简单的类名
        i("getName", aClass.getName());
        i("getsimpleName:", aClass.getSimpleName());
        i("getCanonicalName", aClass.getCanonicalName());
        i("getCanonicalName", Arrays.toString(aClass.getClasses()));
        for (Field field : aClass.getDeclaredFields()) {
            System.out.println("");
            int modifiers = field.getModifiers();
            if (Modifier.isPublic(modifiers)) {
                out_("public");
            } else if (Modifier.isProtected(modifiers)) {
                out_("protected");
            } else if (Modifier.isPrivate(modifiers)) {
                out_("private");
            }
            if (Modifier.isNative(modifiers))
                out_("native");

            if (Modifier.isStatic(modifiers))
                out_("static");
            if (Modifier.isFinal(modifiers))
                out_("final");
            out_(field.getGenericType().toString());
            out_(field.getName());
            out_("(" + modifiers + ")");
        }
        if (aClass.getSuperclass() != null) {
            reflectClass(aClass.getSuperclass());
        }
    }

    public static void i(String str1, String str2) {
        System.out.println(str1 + " : " + str2);
    }

    public static void out(String str2) {
        System.out.println("rent_log : " + str2);
    }

    public static void out_(String str2) {
        System.out.print(" " + str2);
    }
}

你可能感兴趣的:(java,反射,字段,string,class)