码迷,mamicode.com
首页 > 其他好文 > 详细

自动生成构造方法、getter、setter

时间:2018-06-26 01:05:53      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:log4   sdi   方法   buffere   imp   stream   加油   append   har   

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

public class Templates {
    
    public static final String T_CLASS      = "package {0};\n\n{1}public class {2} {\n\n{3}\n\n{5}\n\n{4}\n}";
    public static final String T_GET        = "\tpublic {0} get{1} () {\n\t\treturn {2};\n\t}\n";
    public static final String T_SET        = "\tpublic void set{0}({1} {2}) {\n\t\tthis.{2}={2};\n\t}\n";
    public static final String T_ATTR1      = "\tprivate {0} {1};\n";
    public static final String T_ATTR2      = "\t\tthis.{0}={0};\n";
    public static final String T_IMPORT     = "import java.util.Date;\n\n";
    public static final String T_CONSTRUCT  = "\tpublic {0}({1}) {\n\t\tsuper();\n{2}\n\t}\n";
    
    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("\n");
            }
        } 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,但是还是有点成就感的。工作也一年了,博客就写了几篇,以后要加油了,记录一些有趣的东西。

自动生成构造方法、getter、setter

标签:log4   sdi   方法   buffere   imp   stream   加油   append   har   

原文地址:https://www.cnblogs.com/vvxtoys/p/9226429.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!