开发过程中,经常遇到接口给了xml,需要转化成javabean,字段比较少还好,几十个字段或者更多的话,一个个字段去手打实在太麻烦了,我写了一个小工具来自动生成,省了不少事。
先贴代码
package Test;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
//实现接口ActionListener
public class Test implements ActionListener {
JFrame jf;
JPanel jpanel;
JButton jb1, jb2, jb3, jb4;
JTextArea jta = null;
JScrollPane jscrollPane;
public Test() {
jf = new JFrame("xml生成javabean工具");
Container contentPane = jf.getContentPane();
contentPane.setLayout(new BorderLayout());
jta = new JTextArea(10, 15);
jta.setTabSize(4);
jta.setFont(new Font("标楷体", Font.BOLD, 16));
jta.setLineWrap(true);// 激活自动换行功能
jta.setWrapStyleWord(true);// 激活断行不断字功能
jta.setBackground(Color.pink);
jscrollPane = new JScrollPane(jta);
jpanel = new JPanel();
jpanel.setLayout(new GridLayout(1, 4));
jb1 = new JButton("复制");
jb1.addActionListener(this);
jb2 = new JButton("粘贴");
jb2.addActionListener(this);
jb3 = new JButton("剪切");
jb3.addActionListener(this);
jb4 = new JButton("生成");
jb4.addActionListener(this);
jpanel.add(jb1);
jpanel.add(jb2);
jpanel.add(jb3);
jpanel.add(jb4);
contentPane.add(jscrollPane, BorderLayout.CENTER);
contentPane.add(jpanel, BorderLayout.SOUTH);
jf.setSize(400, 300);
jf.setLocation(400, 200);
jf.setVisible(true);
jf.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
// 覆盖接口ActionListener的方法actionPerformed
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jb1) {
jta.copy();
} else if (e.getSource() == jb2) {
jta.paste();
} else if (e.getSource() == jb3) {
jta.cut();
} else if (e.getSource() == jb4) {
jta.setText(aotuChange(jta.getText()));
}
}
public String aotuChange(String xml) {
xml = xml.replaceAll("<.*</", "public String ");
xml = xml.replace(">", "; ");
return xml;
}
public static void main(String[] args) {
new Test();
}
}
原理很简单,就是正则表达式替换
public String aotuChange(String xml) {
xml = xml.replaceAll("<.*</", "public String ");
xml = xml.replaceAll("<(?!\\!)", "public String ");
xml = xml.replaceAll("/>", "; ");
xml = xml.replaceAll("(?<!-)>", "; ");
}
关键代码就这几行。
我把它生成了一个java小工具,可以直接双击运行。
下载链接:下载链接