在窗口中显示类信息

import java.lang.reflect.Field;
import javax.swing.JFrame;
import javax.swing.BorderFactory;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.border.TitledBorder;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import java.awt.BorderLayout;
import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.Container;
import java.awt.Color;
import javax.swing.text.JTextComponent;
import javax.swing.UIManager;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.lang.reflect.Modifier;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class ViewClassInfoFrame extends JFrame implements ActionListener{
    //输入类名单行文本框
    private JTextField classNameField = new JTextField();
    //查看类信息按钮
    private JButton viewInfoButtom = new JButton();
    //提示输入类名的标签
    private JLabel hintLabel = new JLabel();
    //显示类信息的多行文本框
    private JTextArea InfoTextArea = new JTextArea();
    //滚动容器,不能独立存在
    private JScrollPane infoScrollPane = new JScrollPane();
    //一个标题边框,提示结果信息
    private TitledBorder titledBorder;
    
    //容器,可以盛放其他控件,不能单独存在
    private JPanel upPanel = new JPanel();
    private JPanel centerPanel = new JPanel();
    
    //容器的布局管理器,边界划分,分为东南西北中,默认为CENTER
    private BorderLayout mainFrameBorderLayout = new BorderLayout();
    private BorderLayout centerFrameBorderLayout = new BorderLayout();
    private BorderLayout upFrameBorderLayout = new BorderLayout();
    
    //通过构造函数创建对象实例时,初始化窗口和窗口中的组件
    public ViewClassInfoFrame(){
        //java.awt.Component,激活当前的窗口事件省略了this
//        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        init();                    //初始化窗口
        //java.awt.Container,当前窗口中GUI重新布局,生效
//        validate();
        }
    private void init(){
        //初始化文本输入框
        classNameField.setFont(new java.awt.Font("Dialog", 0, 15));
        classNameField.setSelectedTextColor(java.awt.Color.WHITE);
        classNameField.setText("");                //清空文本
        
        //初始化按钮和标签
        viewInfoButtom.setFont(new java.awt.Font("Dialog", 0, 13));
        viewInfoButtom.setText("查看类信息");
        //将按钮事件注册到监听队列
        viewInfoButtom.addActionListener(this);
        hintLabel.setFont(new java.awt.Font("Dialog", 0, 17));
        hintLabel.setText("请输入完整的类名:");
        
        //初始化文本域,不可编辑,初始为空
        InfoTextArea.setFont(new java.awt.Font("Dialog", 0, 13));
        InfoTextArea.setEditable(false);
        InfoTextArea.setText("");
        
        //初始化标题框,因为BorderFactory.createEtchedBorder()是静态方法,所以没有生成实例变量对象
        titledBorder = new TitledBorder(javax.swing.BorderFactory.createEtchedBorder(Color.white, new Color(134,134,134)), "结果信息");
        
        //初始化滚动容器--包含标题边框
        infoScrollPane.setBorder(titledBorder);    
        //向滚动容器中的视口或悬窗(观看的窗口)添加多行文本框组件
        infoScrollPane.getViewport().add(InfoTextArea,null);
        
        //利用布局管理器将容器放入容器
        upPanel.setLayout(upFrameBorderLayout);
        upPanel.add(hintLabel, BorderLayout.NORTH);
        upPanel.add(classNameField, BorderLayout.CENTER);
        upPanel.add(viewInfoButtom, BorderLayout.SOUTH);
        
        //将滚动容器和内部的组件放到centerPanel面板
        centerPanel.setLayout(centerFrameBorderLayout);
        centerPanel.add(infoScrollPane, BorderLayout.CENTER);
        
        //获取当前窗口的内容容器,设置布局管理器
        this.getContentPane().setLayout(mainFrameBorderLayout);        
        this.setSize(new Dimension(650, 560));
        this.setTitle("使用反射机制查看java的类信息");
        //向窗口内容容器中添加容器
        this.getContentPane().add(upPanel, BorderLayout.NORTH);
        this.getContentPane().add(centerPanel, BorderLayout.CENTER);
        
        //设置当前顶级容器操作的默认操作
        this.getRootPane().setDefaultButton(viewInfoButtom);
        //进程监听窗口的关闭事件
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
        
    //实现ActionListener接口,处理鼠标事件,方法一定要是public    
    public void actionPerformed(ActionEvent e){
        //从文本输入框获取输入的内容
        String className = classNameField.getText();
        StringBuffer buf = new StringBuffer();
        try{
            //利用反射获取类型系的背景是不知道类具体信息,仅知道类名或全限名(包路径+类名)
            Class c = Class.forName(className);
            buf.append(" /**类的声明**/
");
            buf.append(getClassStatement(c));
            buf.append("
");
            buf.append(" /**字段**/
");
            buf.append(getClassFields(c));
            buf.append("
");
            buf.append(" /**构造函数**/
");
            buf.append(getClassConstructors(c));
            buf.append("
");
            buf.append(" /**方法**/
");
            buf.append(getClassMethods(c));
            buf.append("
");
        }catch(Exception e1){
            //调用对话框展示提示信息
            JOptionPane.showMessageDialog(this, "没找到该类:"+e1.getMessage());
            }
        //在多行文本框中展示类信息
        InfoTextArea.setText(buf.toString());
        }
        
    //获取类的声明信息    
    private String getClassStatement(Class c){
        StringBuffer buf = new StringBuffer();
        if(c.    getName().equals("java.lang.Object")){
            buf.append("public class Object{");
        }else{
            String superClass = c.getSuperclass().getName();
            buf.append("public class ").append(c.getName());
            buf.append(" extends ").append(superClass).append(" {");
            }
        return buf.toString();
        }
    
    //获取Field信息
    private String getClassFields(Class c){
        StringBuffer buf = new StringBuffer();
        Field[] fields = c.getDeclaredFields();
        for(Field f:fields){
            //将Field的访问控制符转换为String类型
            String modifier = Modifier.toString(f.getModifiers());
            String type = f.getType().getName();
            buf.append(modifier).append(" ").append(type).append(" ").append(f.getName()).append(";
");
            }
        return buf.toString();
        }    
    
    //获取构造函数信息
    private String getClassConstructors(Class c){
        Constructor[] constructors = c.getDeclaredConstructors();
        StringBuffer buf = new StringBuffer();
        for(Constructor con:constructors){
            //获取构造器的访问控制符
            String modifier = Modifier.toString(con.getModifiers());
            buf.append(modifier).append(" ").append(con.getName()).append(" (");
            //获取构造函数所有参数类型
            Class[] paremeters = con.getParameterTypes();
            for(int i=0;i<paremeters.length;i++){
                if(i==(paremeters.length-1)){
                    buf.append(paremeters[i].getName());
                    }
                else{
                    buf.append(paremeters[i].getName()).append(", ");
                    }
                }
            buf.append(")");
            Class[] excepTypes = con.getExceptionTypes();    
            for(int i=0;i<excepTypes.length;i++){
                if(i==0){
                    buf.append("throws ");
                }
                if(i==(excepTypes.length-1)){
                    buf.append(excepTypes[i].getName());
                }else{buf.append(excepTypes[i].getName()).append(", ");}
                }
                buf.append("
");
            }
            return buf.toString();
        }
    
    //获取所有方法信息
    private String getClassMethods(Class c){
        Method[] methods = c.getDeclaredMethods();
        StringBuffer buf = new StringBuffer();
        for(Method method:methods){
            String modifier = Modifier.toString(method.getModifiers());
            String type = method.getReturnType().getName();
            String name  = method.getName();
            buf.append(modifier).append(" ").append(type).append(" ").append(name).append("(");
            Class[] parameters = method.getParameterTypes();
            for(int i=0;i<parameters.length;i++){
                if(i==0){
                    buf.append(parameters[i].getName()).append(", ");
                    }
                if(i==(parameters.length-1)){
                    buf.append(parameters[i].getName());
                    }else{buf.append(parameters[i].getName()).append(", ");}
                }
            buf.append(") ");
            Class[] excepTypes = method.getExceptionTypes();
            for(int i=0;i<excepTypes.length;i++){
                if(i==0){
                    buf.append("throws ").append(excepTypes[i].getName());
                    }
                if(i==(excepTypes.length-1)){
                    buf.append(excepTypes[i].getName());
                    }else{buf.append(excepTypes[i].getName()).append(", ");}
                }
            buf.append("
");
            }
        return buf.toString();
        }
    public static void main(String[] args){
        //设置界面的外观,为系统外观
//        try{
//            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//        }catch(Exception e){
//            e.printStackTrace();
//            }
        ViewClassInfoFrame frame = new ViewClassInfoFrame();
        //获取屏幕分辨率,使窗体居中
        Dimension screenSize = Toolkit.    getDefaultToolkit().getScreenSize();
        Dimension frameSize = frame.getSize();
        if(frameSize.height > screenSize.height){
            frameSize.height = screenSize.height;
            }
        if(frameSize.width > screenSize.width){
            frameSize.width = screenSize.width;
            }
        frame.setLocation((screenSize.width - frameSize.width)/2, (screenSize.height - frameSize.height)/2);
        frame.setVisible(true);
        }
    } 

执行结果:

原文地址:https://www.cnblogs.com/celine/p/9426833.html