JSFiddle - React, Tailwind, and code Playground

Java Getter/Setter Generator

by Ukjin Yang

HTML

<script src="https://cdn.rawgit.com/composite/7efde856d5840712e707d56fcbc80c03/raw/b5b63d4280173db705cd4ba2915b06225fc17c4b/stripComments.js"></script>
<h1>Java Getter/Setter Generator</h1>
<h2>Insert field list here.</h2>
<textarea id="in" rows="10" cols="50">
/**
 * @foo!
 */
private String foo; //foo
int bar; /* bar */</textarea><button id='run'>Generate!</button>
<h2>Generated getters/setters are below:</h2>
<textarea id="out" rows="10" cols="50" readonly></textarea>
<h2>Options</h2>
<ul>
<li><label><input type="checkbox" id="getter" checked> Getter</label></li>
<li><label><input type="checkbox" id="setter" checked> Setter</label></li>
<li><label><input type="checkbox" id="getems" checked> Getter: force return empty string when null</label></li>
<li><label>Space tab length: <input type="number" id="tablen" value="4" size="1"></label> (0 uses tab.)</li>
</ul>

Babel + JSX

const ID = function(id){return document.getElementById(id);}
const TMPL = /\{(\w+)\}/g;
ID('run').onclick = function(e){
	let out = ID('out'),
      chk = {
        getter: ID('getter').checked,
        setter: ID('setter').checked,
        getems: ID('getems').checked,
        tab: (function(len){
        	let res = len ? '' : '\t';
          for(let i=0;i<len;i++) res += ' ';
          return res;
        })(+ID('tablen').value)
      },
      lin = stripComments(ID('in').value).replace(/\s*\r?\n\s*/g,'').split(/;/),
      result = [],
      tmpl = {
        getter: `public {type} get{ufield} (){
${chk.tab}return {field_expr};
}`,
        setter: `public void set{ufield} ({type} {field}){
${chk.tab}this.{field} = {field};
}`
      };
  for(let i=0,len=lin.length;i<len;i++){
    let decl = lin[i].trim().split(/\s+/, 3);
    if(decl.length < 2 || ~decl.indexOf('final') || ~decl.indexOf('static')){
    	if(lin[i] && lin[i].trim()) console.error(`wrong expression: ${lin[i]}`);
      continue;
    }
    let dtyp = decl.length > 2 ? decl[1] : decl[0],
        dfid = decl.length > 2 ? decl[2] : decl[1];
    if(!dtyp || !dfid){
      console.error(`field or type not found: ${lin[i]}`);
      continue;
    }
    let ufid = dfid[0].toUpperCase() + dfid.substring(1),
        fexr = chk.getems && dtyp.toLowerCase() == 'string' ? `this.${dfid} != null ? this.${dfid} : ""` : `this.${dfid}`,
        modl = {type: dtyp, field: dfid, ufield: ufid, field_expr: fexr},
        func = (dummy, keyword) => modl[keyword] || '';
  	if(chk.getter) result.push(tmpl.getter.replace(TMPL, func));
    if(chk.setter) result.push(tmpl.setter.replace(TMPL, func));
  }
  out.value = result.join('\n');
};