自动生成构造方法gettersetter

Posted vvxtoys

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自动生成构造方法gettersetter相关的知识,希望对你有一定的参考价值。

利用反射自动生成getter、setter、constructor
  • 写个模板类
package common;

public class Templates {
    
    public static final String T_CLASS      = "package {0};

{1}public class {2} {

{3}

{5}

{4}
}";
    public static final String T_GET        = "	public {0} get{1} () {
		return {2};
	}
";
    public static final String T_SET        = "	public void set{0}({1} {2}) {
		this.{2}={2};
	}
";
    public static final String T_ATTR1      = "	private {0} {1};
";
    public static final String T_ATTR2      = "		this.{0}={0};
";
    public static final String T_IMPORT     = "import java.util.Date;

";
    public static final String T_CONSTRUCT  = "	public {0}({1}) {
		super();
{2}
	}
";
    
    public static String format(String pattern, String ... arguments){
        String format = pattern;
        for(int i=0;i<arguments.length;i++){
            format = format.replace("{"+i+"}",arguments[i]);
        }
        return format;
    }
    public static String loadTemplate(String clazz,String pack,String port,
                            String attrs,String get_set,String construct){
        return format(T_CLASS, clazz,pack,port,attrs,get_set,construct);
    }
}
  • 创建一个实体类
package cc.vvxtoys.pojo;

public class Student {
    private int id;
    private String name;
    private String sex;
    private String school;
    
}
  • 工具类
package common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

public class Common {
    
    private static Logger log = Logger.getLogger(Common.class);
    //获得绝对路径
    public static String absolutePath(String pack, String name, String suffix) {
        List<String> list = new ArrayList<>();
        String absolutePath = "";
        try {
            String packPath = pack.replace(".", "\");
            File src = new File(".\src");
            File file = new File(src.getCanonicalPath());
            File[] fs = file.listFiles();
            for (int i = 0; i < fs.length; i++) {
                if (fs[i].isDirectory()) {
                    if (fs[i].getAbsolutePath().endsWith(packPath)) {
                        absolutePath = fs[i].getAbsolutePath() + "\" + name + suffix;
                        return absolutePath;
                    }
                    list.add(fs[i].getAbsolutePath());
                }
            }
            for (int j = 0; j < Integer.MAX_VALUE; j++) {
                if (j>0&&j == list.size() - 1) {
                    break;
                }
                File tmp = new File(list.get(j));
                fs = tmp.listFiles();
                for (int k = 0; k < fs.length; k++) {
                    if (fs[k].isDirectory()) {
                        if (fs[k].getAbsolutePath().endsWith(packPath)) {
                            absolutePath = fs[k].getAbsolutePath() + "\" + name + suffix;
                            return absolutePath;
                        }
                        list.add(fs[k].getAbsolutePath());
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return absolutePath;
    }

    public static String loadFile(String path) {
        File file = new File(path);
        String str = null;
        BufferedReader reader = null;
        StringBuffer buffer = new StringBuffer();
        String charset = "utf-8";
        try {
            InputStreamReader is = new InputStreamReader(new FileInputStream(file), charset);
            reader = new BufferedReader(is);
            while ((str = reader.readLine()) != null) {
                buffer.append(str);
                buffer.append("
");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer.toString();
    }

    public static void writeFile(String filePath, String str, boolean flg) {
        try {
            FileWriter fw = new FileWriter(new File(filePath), flg);
            PrintWriter pw = new PrintWriter(fw);
            pw.println(str);
            log.info("写入成功。。。");
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void writeFile(String filePath, String str) {
        try {
            FileWriter fw = new FileWriter(new File(filePath), true);
            PrintWriter pw = new PrintWriter(fw);
            pw.println(str);
            log.info("写入成功。。。");
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //首字母大写
    public static String upInitials(String str){
        StringBuffer buff = new StringBuffer();
        buff.append(String.valueOf(str.charAt(0)).toUpperCase());
        buff.append(str.toCharArray(),1,str.length()-1);
        return buff.toString();
    }
}
  • 构建类
package auto_get_set;

import java.lang.reflect.Field;

import common.Common;
import common.Templates;
/**
 * @author vvxtoys
 */
public class ClassGenerator {
    
    private String [] attrs;
    private String [] types;
    private String absolutePath;
    private String context;
    private String clazz;
    
    
    public ClassGenerator(Object obj) {
        loadClass(obj);
    }
    public void loadClass(Object obj){
        Field [] fs = null;
        try{
            String claname = obj.getClass().getSimpleName();
            String suffix = ".java";
            String pack   = obj.getClass().getPackage().getName();
            absolutePath = Common.absolutePath(pack, claname, suffix);
            context = Common.loadFile(absolutePath);
            clazz = claname;
            Class clazz = Class.forName(obj.getClass().getName());
            fs = clazz.getDeclaredFields();
            attrs = new String[fs.length];
            types = new String[fs.length];
            for(int i=0;i<fs.length;i++){
                attrs[i] = fs[i].getName();
                types[i] = fs[i].getType().getSimpleName();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public void autoGetSet(){
        String str = context.substring(0,context.lastIndexOf("}"));
        String get_set = "";
        for(int i=0;i<attrs.length;i++){
            String g1 = Templates.format(Templates.T_GET, types[i],Common.upInitials(attrs[i]),attrs[i]);
            String s1 = Templates.format(Templates.T_SET, Common.upInitials(attrs[i]),types[i],attrs[i]);
            get_set+=g1+s1;
        }
        str+=get_set;
        str+="}";
        context = str;
    }
    
    public void autoConstruct(){
        String str = context.substring(0,context.lastIndexOf("}"));
        String c1 = Templates.format(Templates.T_CONSTRUCT, clazz,"","");
        String params = "";
        String field = "";
        for(int i=0;i<attrs.length;i++){
            params+=types[i]+" "+attrs[i]+",";
            field+=Templates.format(Templates.T_ATTR2, attrs[i]);
        }
        params = params.substring(0,params.length()-1);
        String c2 = Templates.format(Templates.T_CONSTRUCT, clazz,params,field);
        str +=c1+c2;
        str+="}";
        context = str;
    }
    
    public void updateClass(){
        Common.writeFile(absolutePath, context,false);
    }
    
    public void run(){
        autoConstruct();
        autoGetSet();
        updateClass();
    }

}
  • 测试
package auto_get_set;

import cc.vvxtoys.pojo.Student;

public class Test {
    
    public static void main(String[] args) {
        ClassGenerator g = new ClassGenerator(new Student());
        g.run();    
    }

}
  • 构建之后的实体类
package cc.vvxtoys.pojo;

public class Student {
    private int id;
    private String name;
    private String sex;
    private String school;
    
    public Student() {
        super();

    }
    public Student(int id,String name,String sex,String school) {
        super();
        this.id=id;
        this.name=name;
        this.sex=sex;
        this.school=school;

    }
    public int getId () {
        return id;
    }
    public void setId(int id) {
        this.id=id;
    }
    public String getName () {
        return name;
    }
    public void setName(String name) {
        this.name=name;
    }
    public String getSex () {
        return sex;
    }
    public void setSex(String sex) {
        this.sex=sex;
    }
    public String getSchool () {
        return school;
    }
    public void setSchool(String school) {
        this.school=school;
    }
}
  • 结束
写写停停大概也是花费了两天的时间,东西虽然很小,也还有bug,但是还是有点成就感的。工作也一年了,博客就写了几篇,以后要加油了,记录一些有趣的东西。

以上是关于自动生成构造方法gettersetter的主要内容,如果未能解决你的问题,请参考以下文章

Intellij IDEA 的一些快捷键

创建一个叫做机动车的类: 属性:车牌号(String),车速(int),载重量(double) 功能:加速(车速自增)减速(车速自减)修改车牌号,查询车的载重量。 编写两个构造方法:一个没有(代码片段

C#VS快捷键

C#VS快捷键

C#VS快捷键

C#VS快捷键