Java利用反射取得类的所有信息

Java中可以利用反射获取类的名称、构造函数、属性、方法。也就是说可以通过反射可以取得类的所有信息(不管该成员是否封装为private).

如有下面的Dept类定义:

package org.lyk.vo;

import org.lyk.utils.MyFlag;
import org.lyk.utils.MyService;

import java.io.Serializable;
import java.text.NumberFormat;


public class Dept implements Serializable
{
    private Integer deptno;
    private String dname;
    private String loc;
    private Company company;

    protected void print()
    {

    }
    private void show()
    {
        System.out.println("");
    }

    public Dept() throws NumberFormatException,NullPointerException,ClassNotFoundException
    {
    }

    public Dept(Integer deptno, String dname, String loc, Company company)
    {
        this.deptno = deptno;
        this.dname = dname;
        this.loc = loc;
        this.company = company;
    }

    public Company getCompany()
    {
        return company;
    }

    public void setCompany(Company company)
    {
        this.company = company;
    }

    public Integer getDeptno()
    {
        return deptno;
    }

    public void setDeptno(Integer deptno)
    {
        this.deptno = deptno;
    }

    public String getDname()
    {
        return this.dname;
    }

    public void setDname(String dname)
    {
        this.dname = dname;
    }

    public String getLoc()
    {
        return loc;
    }

    public void setLoc(String loc)
    {
        this.loc = loc;
    }

    @Override
    @Deprecated
    public String toString()
    {
        return "Dept{" +
                "deptno=" + deptno +
                ", dname='" + dname + '\'' +
                ", loc='" + loc + '\'' +
                '}';
    }
    public void showError()throws NumberFormatException
    {}
}

下面的代码是通过反射获取该类的所有信息:

package org.lyk.main;


import org.lyk.utils.*;
import org.lyk.vo.Container;
import org.lyk.vo.Dept;
import org.lyk.vo.IFruit;
import sun.misc.Unsafe;

import java.lang.annotation.Annotation;
import java.lang.reflect.*;


public class Hello
{
    public static void main(String[] args) throws Exception
    {
        Class cls = Dept.class;
        //打印类名称信息
        printName(cls);
        //打印属性信息
        printFields(cls);
        System.out.println("\n");
        //打印构造函数
        printConstructors(cls);
        System.out.println("\n");
        //打印方法
        printMethods(cls);
        System.out.println("}");

    }

    public static void printConstructors(Class cls)
    {
        Constructor[] constructors = cls.getConstructors();
        for (Constructor c : constructors)
        {
            StringBuffer buf = new StringBuffer();
            buf.append("\t");
            buf.append(Modifier.toString(c.getModifiers()));
            buf.append(" ");
            String fullName = c.getName();
            buf.append(fullName.substring(fullName.lastIndexOf(".") + 1));
            buf.append("(");
            setParameters(c,buf);
            buf.append(")");
            setExceptions(c,buf);
            System.out.println(buf);
        }
    }

    public static void printName(Class cls)
    {
        StringBuffer buf = new StringBuffer();
        buf.append(Modifier.toString(cls.getModifiers()));
        buf.append(" class ");
        buf.append(cls.getSimpleName());
        Class superClass = cls.getSuperclass();
        if (superClass != null)
        {
            if (!superClass.getSimpleName().equalsIgnoreCase("Object"))
            {
                buf.append(" extends ");
                buf.append(superClass.getSimpleName());
            }
        }
        Class[] interfaces = cls.getInterfaces();
        if (interfaces.length > 0)
        {
            buf.append(" implements ");
            for (Class itf : interfaces)
            {
                buf.append(itf.getSimpleName());
                buf.append(",");
            }
            buf.delete(buf.length() - 1, buf.length());
        }

        buf.append("\n{");
        System.out.println(buf.toString());
    }

    public static void printFields(Class cls)
    {
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields)
        {
            StringBuffer buf = new StringBuffer();
            buf.append("\t");
            buf.append(Modifier.toString(field.getModifiers()));
            buf.append(" ");
            buf.append(field.getType().getSimpleName());
            buf.append(" ");
            buf.append(field.getName());
            buf.append(";");
            System.out.println(buf.toString());
        }
    }
    public static void printMethods(Class cls)
    {
        Method[] methods = cls.getDeclaredMethods();
        for(Method m : methods)
        {
            StringBuffer buf = new StringBuffer("\t");
            buf.append(Modifier.toString(m.getModifiers()));
            buf.append(" ");
            buf.append(m.getReturnType().getSimpleName());
            buf.append(" ");
            buf.append(m.getName());
            buf.append("(");
            setParameters(m,buf);
            buf.append(")");
            setExceptions(m,buf);
            System.out.println(buf.toString());
        }
    }
    public static void setParameters(Executable c,StringBuffer buf)
    {

        Class[] parameterTypes = c.getParameterTypes();
        if (parameterTypes.length > 0)
        {
            int index = 0;
            for (Class parameterType : parameterTypes)
            {
                buf.append(parameterType.getSimpleName());
                buf.append(" arg");
                buf.append(index++);
                buf.append(",");
            }
            buf.delete(buf.length() - 1, buf.length());
        }
    }
    public static void setExceptions(Executable c,StringBuffer buf)
    {

        Class[] exceptionTypes = c.getExceptionTypes();
        if(exceptionTypes.length > 0)
        {
            buf.append(" throws ");
            for(Class exceptionType : exceptionTypes)
            {
                buf.append(exceptionType.getSimpleName());
                buf.append(",");
            }
            buf.delete(buf.length()-1,buf.length());
        }
    }
}

输出信息:

public class Dept implements Serializable
{
    private Integer deptno;
    private String dname;
    private String loc;
    private Company company;


    public Dept() throws NumberFormatException,NullPointerException,ClassNotFoundException
    public Dept(Integer arg0,String arg1,String arg2,Company arg3)


    public String toString()
    protected void print()
    public String getDname()
    private void show()
    public Company getCompany()
    public void setCompany(Company arg0)
    public Integer getDeptno()
    public void setDeptno(Integer arg0)
    public void setDname(String arg0)
    public String getLoc()
    public void setLoc(String arg0)
    public void showError() throws NumberFormatException
}

Process finished with exit code 0