/** * Gets the private field representing the given <code>propertyName</code> within the given class. * * @return the private Field for this propertyName, or null if no such field (should not throw * NoSuchFieldException) */ protected Field<?> getPrivateField(final FieldHolder<?> fieldHolder, final String propertyName) { if (this.privateFieldConvention != null) { // Determine field name based on convention. MessageFormat arguments are: // // {0} = dateOfBirth, surname // {1} = DateOfBirth, Surname String[] arguments = new String[] {propertyName, StringUtils.capitalize(propertyName)}; String fieldName; synchronized (this.privateFieldConvention) { fieldName = this.privateFieldConvention.format(arguments, new StringBuffer(), null).toString(); } return fieldHolder.getField(fieldName); } Field<?> field = fieldHolder.getField(propertyName); // FORGE-402: support fields starting with capital letter if (field == null && !StringUtils.isCapitalized(propertyName)) { field = fieldHolder.getField(StringUtils.capitalize(propertyName)); } return field; }
@Command("new-field") @RequiresResource(JavaResource.class) public void newField( @PipeIn final String in, final PipeOut out, @Option( required = false, help = "the field definition: surround with single quotes", description = "field definition") final String... def) throws FileNotFoundException { JavaSourceFacet java = project.getFacet(JavaSourceFacet.class); String fieldDef = null; if (def != null) { fieldDef = Strings.join(Arrays.asList(def), " "); } else if (in != null) { fieldDef = in; } else { throw new RuntimeException("arguments required"); } JavaSource<?> source = resource.getJavaSource(); if (source instanceof FieldHolder) { FieldHolder<?> clazz = ((FieldHolder<?>) source); String name = JavaParser.parse(JavaClass.class, "public class Temp{}").addField(fieldDef).getName(); if (clazz.hasField(name)) { throw new IllegalStateException("Field named [" + name + "] already exists."); } clazz.addField(fieldDef); java.saveJavaSource(source); } }