Skip to content

Instantly share code, notes, and snippets.

@ywjno
Created July 18, 2012 07:58
Show Gist options
  • Save ywjno/3134928 to your computer and use it in GitHub Desktop.
Save ywjno/3134928 to your computer and use it in GitHub Desktop.
create getter setter methods for java, by writing order for this java bean
#encoding: utf-8
require 'find'
class CreateGetterSetterMethodsForJava
def initialize
@work_path = File.dirname(File.expand_path(__FILE__))
if ARGV.length != 0
if File.file?(ARGV[0])
@work_path = File.dirname(File.expand_path(ARGV[0]))
else
@work_path = File.expand_path ARGV[0]
end
end
end
def create
Find.find(@work_path) do |file|
if File.file?(file) && File.extname(file) == '.java'
field_type = {}
lines = File.readlines file
lines.each do |line|
line.scan(/[a-zA-Z ]+\s(?<type>.+)\s(?<field>[a-zA-Z0-9_]+?)(\s*?=\s*?.+)?;/) do |type, field|
field_type[field.to_s] = type.to_s
end
end
index = -1
lines.reverse.each_with_index do |line, i|
if line =~ /.*}{1}.*/
index = lines.size - i
break
end
end
new_lines = Array.new(lines[0, index - 1])
field_type.each do |field, type|
new_lines << getter_str(field, type)
new_lines << setter_str(field, type)
end
new_lines += lines[index - 1.. -1]
File.open(file, 'w') do |file|
new_lines.each do |line|
file.puts line
end
end
puts "#{File.basename(file)} has created over."
end
end
puts "all file has created over."
end
def getter_str(field, type)
str = <<-"getter_str"
public #{type} get#{field[0].upcase}#{field[1..-1]}() {
return #{field};
}
getter_str
if type == 'boolean'
str = <<-"getter_str"
public boolean is#{field[0].upcase}#{field[1..-1]}() {
return #{field};
}
getter_str
end
str
end
def setter_str(field, type)
return <<-"setter_str"
public void set#{field[0].upcase}#{field[1..-1]}(#{type} #{field}) {
this.#{field} = #{field};
}
setter_str
end
end
CreateGetterSetterMethodsForJava.new.create
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment