c123728529 发表于 2013-2-1 11:47:50

反射示例

很熟悉的示例吧!熟悉一下反射机制以及reflect的SDKpublic class ViewClassInfoFrame extends JFrame implements ActionListener{    JTextField classnameField = new JTextField();    JButtonviewinfoButton = new JButton();    JLabel hintLabel = new JLabel();    JTextArea infoTextArea= new JTextArea();    JScrollPane infoScrollPane = new JScrollPane();    TitledBorder titledBorder;      JPanelupPanel = new JPanel();    JPanelcenterPanel= new JPanel();      BorderLayout mainFrameBorderLayout = new BorderLayout();    BorderLayout centerPanelBorderLayout = new BorderLayout();    BorderLayout upPanelBorderLayout = new BorderLayout();       /** 构造函数 */    public ViewClassInfoFrame() {      enableEvents(AWTEvent.WINDOW_EVENT_MASK);      init();      validate();    }    /**初始化窗口*/    private void init(){                classnameField.setFont(new Font("Dialog",0,15));      classnameField.setSelectedTextColor(Color.white);      classnameField.setText("");                viewinfoButton.setFont(new Font("Dialog",0,13));      viewinfoButton.setText("查看类详细信息");      viewinfoButton.addActionListener(this);      hintLabel.setFont(new Font("Dialog",0,13));      hintLabel.setText("类路径");                infoTextArea.setFont(new Font("Dialog",0,14));      infoTextArea.setEditable(false);      infoTextArea.setText("");                titledBorder = new TitledBorder(BorderFactory.createEtchedBorder(Color.white,new Color(134,134,134)),"结果信息");      infoScrollPane.setBorder(titledBorder);      infoScrollPane.getViewport().add(infoTextArea,null);                upPanel.setLayout(upPanelBorderLayout);      centerPanel.setLayout(centerPanelBorderLayout);      upPanel.add(hintLabel,BorderLayout.NORTH);      upPanel.add(classnameField,BorderLayout.CENTER);      upPanel.add(viewinfoButton,BorderLayout.SOUTH);                centerPanel.add(infoScrollPane);                this.getContentPane().setLayout(mainFrameBorderLayout);      this.setSize(new Dimension(450,360));      this.setTitle("使用反射机制查看类信息");                this.getContentPane().add(upPanel,BorderLayout.NORTH);      this.getContentPane().add(centerPanel,BorderLayout.CENTER);                this.getRootPane().setDefaultButton(viewinfoButton);      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    }    public void actionPerformed(ActionEvent e) {      String classname = classnameField.getText();      StringBufferbuffer=new StringBuffer();      try {            //动态加载类获取类对象            Class c = Class.forName(classname);            buffer.append("/**类声明**/ \n");            buffer.append(getClassStatement(c));            buffer.append("\n");                        buffer.append("/**字段**/");            buffer.append(getFields(c));                        buffer.append("/**构造函数**/");            buffer.append(getConstructors(c));            buffer.append("/**方法**/");            buffer.append(getMethods(c));            buffer.append("} \n");      } catch (Exception e1) {            JOptionPane.showMessageDialog(this, "没有找到类:" + e1.getMessage());      }      infoTextArea.setText(buffer.toString());    }    public String getClassStatement(Class c){      StringBuffer buffer = new StringBuffer();      if(c.getName().equals("java.lang.object")){            buffer.append("public class Ojbect{");            return buffer.toString();      }else {            String supername = c.getSuperclass().getName();            buffer.append("public class").append(c.getName());            buffer.append("extends").append(supername).append(";");      }      return buffer.toString();    }    /**   * 获取类的属性   * @param c   * @return   */    public String getFields(Class c){      StringBufferbuffer = new StringBuffer();      Field field = null;      Field [] fields = c.getFields();         for (int i = 0; i < fields.length; i++) {            field = fields;            buffer.append(Modifier.toString(field.getModifiers())).append(" ");            Class type = field.getType();            buffer.append(type.getName()).append(" ");            buffer.append(field.getName()).append(";\n");//获取属性名      }      return buffer.toString();    }    /**   * 获取类的构造方法   * @param c   * @return String   */    public String getConstructors(Class c){      StringBuffer buffer = new StringBuffer();      Constructor [] constructors = c.getDeclaredConstructors();      Constructor constructor = null;      for (int i = 0; i < constructors.length; i++) {            constructor = constructors;            buffer.append(Modifier.toString(constructor.getModifiers())).append(" ");            buffer.append(constructor.getName()).append("(");            //获取参数类型            Class[] paramsTypes= constructor.getParameterTypes();            Class class1= null;            for (int j = 0; j < paramsTypes.length; j++) {                class1 = paramsTypes;                if (j==(paramsTypes.length-1)) {                  buffer.append(class1.getName());                }else {                  buffer.append(class1.getName()).append(",");                }            }            buffer.append(")");            //获取方法声明的异常            Class[] exceTypes = constructor.getExceptionTypes();            for (int j = 0; j < exceTypes.length; j++) {                class1 = exceTypes;                if (j==0) {                  buffer.append("throws");                }               if(j==(exceTypes.length-1)){                  buffer.append(class1.getName());                } else {                  buffer.append(class1.getName()).append(", ");                }            }            buffer.append("\n");                  }                        return buffer.toString();    }    /**   * 获取类的方法   * @param c   * @return String   */    public String getMethods(Class c){      StringBuffer buffer = new StringBuffer();      Method[] methods= c.getMethods();      Method method = null;      for (int i = 0; i < methods.length; i++) {            method = methods;            buffer.append(Modifier.toString(method.getModifiers())).append(" ");            Class returnType = method.getReturnType();            buffer.append(returnType.getName()).append(" ");            buffer.append(method.getName()).append("(");            //获取方法参数            Class[] paramTypes =method.getParameterTypes();            Class class1 = null;            for (int j = 0; j < paramTypes.length; j++) {                class1 = paramTypes;                if (j==(paramTypes.length-1)) {                  buffer.append(class1.getName());                } else {                  buffer.append(class1.getName()).append(", ");                }            }            buffer.append(")");          //获取方法声明的异常            Class[] exceTypes = method.getExceptionTypes();            for (int j = 0; j < exceTypes.length; j++) {                class1 = exceTypes;                if (j==0) {                  buffer.append("throws");                }               if(j==(exceTypes.length-1)){                  buffer.append(class1.getName());                } else {                  buffer.append(class1.getName()).append(", ");                }            }            buffer.append("\n");      }      return buffer.toString();    }            /**   * @param args   */    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);    }}
页: [1]
查看完整版本: 反射示例