java bean代码生成器(只需要提供一个url和最外部的类名即可)

写了一个java bean代码生成器,只需要一个url和类名即可。大体框架如下,可能有点小bug,欢迎大家拍砖

#encoding=UTF-8
require 'erb'
require 'open-uri'

class Cls
	def initialize(package=nil,class_name=nil)
		@package,@class_name = package,class_name

		@attrs = []
		@nest_cls_list = []
		@nest_cls_str = ""
	end
	attr_accessor :package, :class_name, :attrs

	def cls_list=(cls_list)
		@cls_list=cls_list
	end

	def add_nest_cls(cls)
		@nest_cls_list.push(cls)
	end

	def nest_cls_str=(str)
		@nest_cls_str=str
	end

	def nest_cls_str
		@nest_cls_str
	end

	# static methods
	class << self
		def get(url)
			html_response = nil
			open(url) do |http|
				html_response = http.read
			end
			return html_response
		end

		def build_tree(url,package,class_name)
			top_cls_name = class_name
			response = get(url).gsub(/\s*/,'')

			cls_list   = []
			cls_list_copy = []
			cur_cls    = Cls.new(package,class_name)
			cls_list   << cur_cls
			cls_list_copy.push(cur_cls)
			attr_index = 0

			response.gsub!(/}/,"\n}\n")
			response.gsub!(/\n+/,"\n")
			array = response.split(",")
			cls_index = 0

			start_parse_array = false
			end_array_elem = false

			array.each do |elem|
				cur_cls_name = nil

				if start_parse_array == true && end_array_elem == true
					if elem =~ /\]/
						start_parse_array = false
						cls_list.pop
						cur_cls = cls_list.last
						cur_cls_name = cur_cls.class_name
						next
					else
						next
					end
				end

				if elem =~ /(.+){/
					key = $1
					if key =~ /"(.*?)"\s*:\s*\[/	# JSONArray
						start_parse_array = true
						attr_name = $1
						cur_cls_name = $1.capitalize
						if cur_cls_name[cur_cls_name.size - 1] == 's'
							cur_cls_name = cur_cls_name[0..cur_cls_name.size - 2]
						end
						last_cls = cur_cls
						cur_cls = Cls.new(nil,cur_cls_name)
						cls_list.push(cur_cls)
						cls_list_copy.push(cur_cls)

						type = Cls::Attr.get_attr_type(attr_name,cur_cls_name,true)
						attr = Cls::Attr.new(type,attr_name)
						last_cls.add_attr(attr)
						last_cls.add_nest_cls(cur_cls)

						log(last_cls,attr)

					elsif key =~ /"(.*?)"/			# JSONObject
						attr_name = $1
						last_cls = cls_list.last
						cur_cls_name = attr_name.capitalize
						type = Cls::Attr.get_attr_type(attr_name,cur_cls_name,false)
						attr = Cls::Attr.new(type,attr_name)
						last_cls.add_attr(attr)

						log(last_cls,attr)
						cur_cls = Cls.new(nil,cur_cls_name)

						last_cls.add_nest_cls(cur_cls)

						cls_list.push(cur_cls)
						cls_list_copy.push(cur_cls)
					end
				elsif elem =~ /{/     
					cur_cls_name = cur_cls.class_name
				elsif elem =~ /}/
					if start_parse_array == true
						end_array_elem = true
					end
				end

				if cur_cls_name == nil # oridinary attrs
					key_value = elem.split(":")
					if key_value.size == 2
						key = key_value[0].gsub(/"/,'')
						value = key_value[1]
						type = Cls::Attr.get_attr_type(value)
						attr = Cls::Attr.new(type,key)
						cur_cls.add_attr(attr)
						log(cur_cls,attr)
					end
				else					# class begin
					if cur_cls_name == top_cls_name
						key_value = elem.split(":")
						if key_value.size == 2
							key = key_value[0].gsub(/"/,'')
							if key =~ /{\s*(.*)/
								key = $1
							end
							value = key_value[1]
							type = Cls::Attr.get_attr_type(value)
							attr = Cls::Attr.new(type,key)
							cur_cls.add_attr(attr)
							log(cur_cls,attr)
						end
					else
						next if elem =~ /\]/

						key_value = elem.split(":")
						if key_value.size == 2
							key = key_value[0].gsub(/"/,'')
							value = key_value[1]
							type = Cls::Attr.get_attr_type(value)
							attr = Cls::Attr.new(type,key)
							cur_cls.add_attr(attr)
							log(cur_cls,attr)
						elsif key_value.size == 3
							cls_name = key_value[0]
							cls_name = $1 if cls_name =~ /"(.*?)"/
							value = key_value[2]
							attr_name = key_value[1]


							if attr_name =~ /\[/
								if cls_name[cls_name.size-1] == 's'
									cls_name = cls_name[0] + cls_name[1..key.size-2]
									cls_name = cls_name.capitalize
								end
								if attr_name =~ /\[\{"(.*?)"/
									attr_name = $1
								end
							else
								if attr_name =~ /\{"(.*?)"/
									attr_name = $1
								end
								cls_name = cls_name.capitalize
							end
							type = Cls::Attr.get_attr_type(value)
							attr = Cls::Attr.new(type,attr_name)
							cur_cls.add_attr(attr)
							log(cur_cls,attr)
						end
					end
				end
			end
			cls_list_copy
		end

		def parse(url,package,class_name)
			cls_list = build_tree(url,package,class_name)

			top_cls = cls_list.first
			top_cls.cls_list = cls_list

			top_str = top_cls.build
			puts top_str
		end


		def log(cur_cls,attr)
			#puts "cur_cls.name = #{cur_cls.class_name},attr.type = #{attr.type}, attr.name = #{attr.name}"
		end
	end

	def template
		template = %{ 
			<% if package != nil %>
				package <%= package %>;
				public class <%= class_name %> {
			<% else %>
				public static class <%= class_name %> {
			<% end %>

			<% attrs.each do |attr| %>
				private <%= attr.type %> <%= attr.name %>;
			<% end %>

			<% attrs.each do |attr| %>
				public <%= attr.type %> get<%= attr.name.capitalize %>() {
					return <%= attr.name %>;
				}

				public void set<%= attr.name.capitalize %> (<%= attr.type %> <%= attr.name %>) {
					this.<%= attr.name %> = <%= attr.name %>;
				}
			<% end %>

			<% @nest_cls_list.each do |nest_cls| %>
				<%= nest_cls.build %>
			<% end %>
			<% if package == "nil" %>
				}
			<% end %>
			}
		}
	end

	def add_attr(attr)
		@attrs << attr
	end

	def get_binding
		binding
	end

	def build
		erb = ERB.new(template)
		str = erb.result(get_binding)
	end

	class Attr
		def initialize(type,name)
			@type,@name=type,name
		end
		attr_accessor :type, :name

		public
		def is_ordinary_type?
			a = ["int","long","String","double"].freeze
			a.include?(type)
		end


		class << self
			def get_attr_type(attr_value,cls_type=nil,is_json_array=nil)
				ordinary_type = get_ordinary_type(attr_value)
				if (ordinary_type == nil)
					if (is_json_array != nil)
						return get_cls_name_from_json_array(cls_type) if cls_type != nil && is_json_array == true
						return get_cls_name_from_json_obj(cls_type) if cls_type != nil && is_json_array == false
					end
				else
					ordinary_type
				end
			end

			def get_ordinary_type(attr_value)
				if attr_value =~ /".*?"/
					"String".freeze
				elsif attr_value =~ /\d+[.]\d+/
					"double".freeze
				elsif attr_value =~ /(\d+){5,}/
					"long".freeze
				elsif attr_value =~ /\d+/
					"int".freeze
				end
			end

			def get_cls_name_from_json_array(type)
				"List<#{type}>".freeze
			end

			def get_cls_name_from_json_obj(type)
				type.freeze
			end
		end
	end
end

url = "http://192.168.1.103:8080/2.txt"
Cls.parse(url,"com.caixiang.lottery.jointbuy","JointBuyModel")



测试json文件如下: 2.txt:

{
  "code": 0,
  "msg": "成功",
  "data": {
    "totalPage": 1,
    "items": [
      {
        "uid": 1242,
        "oneMoney": 0.01,
        "orderCode": "HM20141118161509_2234690",
        "haveBuyNum": 900,
        "lotType": 43,
        "content": "test",
        "guaranteeNum": 0,
        "totalNum": 1000,
        "title": "test",
        "ratio": 90,
        "userName": "小红手",
        "showType": 2,
        "partNum": 1,
        "commission": 10,
        "channel": 10000000,
        "allmoney": 10
      },
      {
        "uid": 1242,
        "oneMoney": 0.01,
        "orderCode": "HM20141118161509_2234690",
        "haveBuyNum": 900,
        "lotType": 43,
        "content": "test",
        "guaranteeNum": 0,
        "totalNum": 1000,
        "title": "test",
        "ratio": 90,
        "userName": "小红手",
        "showType": 2,
        "partNum": 1,
        "commission": 10,
        "channel": 10000000,
        "allmoney": 10
      }
    ],
    "currentPageNo": 1
  }
}

生成的代码如下:

package com.caixiang.lottery.jointbuy;

public class JointBuyModel {


    private int code;

    private String msg;

    private Data data;


    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Data getData() {
        return data;
    }

    public void setData(Data data) {
        this.data = data;
    }


    public static class Data {


        private int totalPage;

        private List<Item> items;

        private int currentPageNo;


        public int getTotalpage() {
            return totalPage;
        }

        public void setTotalpage(int totalPage) {
            this.totalPage = totalPage;
        }

        public List<Item> getItems() {
            return items;
        }

        public void setItems(List<Item> items) {
            this.items = items;
        }

        public int getCurrentpageno() {
            return currentPageNo;
        }

        public void setCurrentpageno(int currentPageNo) {
            this.currentPageNo = currentPageNo;
        }


        public static class Item {


            private int uid;

            private int oneMoney;

            private String orderCode;

            private int haveBuyNum;

            private int lotType;

            private String content;

            private int guaranteeNum;

            private int totalNum;

            private String title;

            private int ratio;

            private String userName;

            private int showType;

            private int partNum;

            private int commission;

            private long channel;

            private int allmoney;


            public int getUid() {
                return uid;
            }

            public void setUid(int uid) {
                this.uid = uid;
            }

            public int getOnemoney() {
                return oneMoney;
            }

            public void setOnemoney(int oneMoney) {
                this.oneMoney = oneMoney;
            }

            public String getOrdercode() {
                return orderCode;
            }

            public void setOrdercode(String orderCode) {
                this.orderCode = orderCode;
            }

            public int getHavebuynum() {
                return haveBuyNum;
            }

            public void setHavebuynum(int haveBuyNum) {
                this.haveBuyNum = haveBuyNum;
            }

            public int getLottype() {
                return lotType;
            }

            public void setLottype(int lotType) {
                this.lotType = lotType;
            }

            public String getContent() {
                return content;
            }

            public void setContent(String content) {
                this.content = content;
            }

            public int getGuaranteenum() {
                return guaranteeNum;
            }

            public void setGuaranteenum(int guaranteeNum) {
                this.guaranteeNum = guaranteeNum;
            }

            public int getTotalnum() {
                return totalNum;
            }

            public void setTotalnum(int totalNum) {
                this.totalNum = totalNum;
            }

            public String getTitle() {
                return title;
            }

            public void setTitle(String title) {
                this.title = title;
            }

            public int getRatio() {
                return ratio;
            }

            public void setRatio(int ratio) {
                this.ratio = ratio;
            }

            public String getUsername() {
                return userName;
            }

            public void setUsername(String userName) {
                this.userName = userName;
            }

            public int getShowtype() {
                return showType;
            }

            public void setShowtype(int showType) {
                this.showType = showType;
            }

            public int getPartnum() {
                return partNum;
            }

            public void setPartnum(int partNum) {
                this.partNum = partNum;
            }

            public int getCommission() {
                return commission;
            }

            public void setCommission(int commission) {
                this.commission = commission;
            }

            public long getChannel() {
                return channel;
            }

            public void setChannel(long channel) {
                this.channel = channel;
            }

            public int getAllmoney() {
                return allmoney;
            }

            public void setAllmoney(int allmoney) {
                this.allmoney = allmoney;
            }
        }
    }
}


 
 

猜你喜欢

转载自blog.csdn.net/lyx2007825/article/details/41382683