Skip to content

Commit

Permalink
Add GenerationConfig option to exclude Object Header from toString() …
Browse files Browse the repository at this point in the history
…method of generated Java classes
  • Loading branch information
ajaysagar authored and ajay.sagar committed Jun 16, 2024
1 parent 34cc693 commit f44d83e
Show file tree
Hide file tree
Showing 10 changed files with 141 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ public class Jsonschema2PojoTask extends Task implements GenerationConfig {

private String[] toStringExcludes = new String[] {};

private boolean excludeObjectHeaderFromToString = false;

private AnnotationStyle annotationStyle = AnnotationStyle.JACKSON;

private boolean useTitleAsClassname = false;
Expand Down Expand Up @@ -196,6 +198,7 @@ public class Jsonschema2PojoTask extends Task implements GenerationConfig {
private boolean includeGeneratedAnnotation = true;

private boolean useJakartaValidation = false;

/**
* Execute this task (it's expected that all relevant setters will have been
* called by Ant to provide task configuration <em>before</em> this method
Expand Down Expand Up @@ -517,6 +520,17 @@ public void setIncludeToString(boolean includeToString) {
this.includeToString = includeToString;
}

/**
* Sets the 'excludeObjectHeaderFromToString' property of this class
*
* @param excludeObjectHeaderFromToString
* Whether to exclude object header from the <code>toString</code> method in generated
* Java types.
*/
public void setExcludeObjectHeaderFromToString(boolean excludeObjectHeaderFromToString) {
this.excludeObjectHeaderFromToString = excludeObjectHeaderFromToString;
}

/**
* Sets the 'annotationStyle' property of this class
*
Expand Down Expand Up @@ -1056,6 +1070,11 @@ public String[] getToStringExcludes() {
return toStringExcludes;
}

@Override
public boolean isExcludeObjectHeaderFromToString() {
return excludeObjectHeaderFromToString;
}

@Override
public AnnotationStyle getAnnotationStyle() {
return annotationStyle;
Expand Down
5 changes: 5 additions & 0 deletions jsonschema2pojo-ant/src/site/Jsonschema2PojoTask.html
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,11 @@ <h3>Parameters</h3>
<td valign="top">A string containing fields to be excluded from toString generation.</td>
<td align="center" valign="top">No (default <code>""</code> (none))</td>
</tr>
<tr>
<td valign="top">excludeObjectHeaderFromToString</td>
<td valign="top">Whether to exclude the object header from the generated toString() methods.</td>
<td align="center" valign="top">No (default <code>"false"</code> (none))</td>
</tr>
<tr>
<td valign="top">initializeCollections</td>
<td valign="top">Whether to initialize Set and List fields as empty collections, or leave them
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ public class Arguments implements GenerationConfig {
@Parameter(names = { "-tse", "--tostring-excludes" }, description = "The fields that should be excluded from generated toString methods")
private String toStringExcludes = "";

@Parameter(names = { "-tso", "--exclude-object-header-from-tostring" }, description = "Exclude the object header from generated toString methods")
private boolean excludeObjectHeaderFromToString = false;

@Parameter(names = { "-a", "--annotation-style" })
private AnnotationStyle annotationStyle = AnnotationStyle.JACKSON;

Expand Down Expand Up @@ -368,7 +371,12 @@ public boolean isIncludeToString() {
public String[] getToStringExcludes() {
return defaultString(toStringExcludes).split(" ");
}


@Override
public boolean isExcludeObjectHeaderFromToString() {
return excludeObjectHeaderFromToString;
}

@Override
public AnnotationStyle getAnnotationStyle() {
return annotationStyle;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,14 @@ public String[] getToStringExcludes() {
return new String[] {};
}

/**
* @return {@code false}
*/
@Override
public boolean isExcludeObjectHeaderFromToString() {
return false;
}

/**
* @return {@code false}
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,13 @@ public interface GenerationConfig {
*/
String[] getToStringExcludes();

/**
* Gets the 'excludeObjectHeaderFromToString' configuration option.
*
* @return Whether to exclude the object header from the toString implementations of the generated Java types
*/
boolean isExcludeObjectHeaderFromToString();

/**
* Gets the 'annotationStyle' configuration option.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -274,14 +274,18 @@ private void addToString(JDefinedClass jclass) {
JClass stringBuilderClass = jclass.owner().ref(StringBuilder.class);
JVar sb = body.decl(stringBuilderClass, "sb", JExpr._new(stringBuilderClass));

// Write the header, e.g.: example.domain.MyClass@85e382a7[
body.add(sb
.invoke("append").arg(jclass.dotclass().invoke("getName"))
.invoke("append").arg(JExpr.lit('@'))
.invoke("append").arg(
jclass.owner().ref(Integer.class).staticInvoke("toHexString").arg(
jclass.owner().ref(System.class).staticInvoke("identityHashCode").arg(JExpr._this())))
.invoke("append").arg(JExpr.lit('[')));
if (!ruleFactory.getGenerationConfig().isExcludeObjectHeaderFromToString()) {
// Write the header, e.g.: example.domain.MyClass@85e382a7[
body.add(sb
.invoke("append").arg(jclass.dotclass().invoke("getName"))
.invoke("append").arg(JExpr.lit('@'))
.invoke("append").arg(
jclass.owner().ref(Integer.class).staticInvoke("toHexString").arg(
jclass.owner().ref(System.class).staticInvoke("identityHashCode").arg(JExpr._this())))
.invoke("append").arg(JExpr.lit('[')));
} else {
body.add(sb.invoke("append").arg(JExpr.lit('[')));
}

// If this has a parent class, include its toString()
if (!jclass._extends().fullName().equals(Object.class.getName())) {
Expand Down
3 changes: 3 additions & 0 deletions jsonschema2pojo-gradle-plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,9 @@ jsonSchema2Pojo {
// properties to exclude from generated toString
toStringExcludes = ["someProperty"]
// Whether to exclude the object header from the toString method
excludeObjectHeaderFromToString = false
// What Java version to target with generated source code (1.6, 1.8, 9, 11, etc).
// By default, the version will be taken from the Gradle Java plugin's 'sourceCompatibility',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ public class JsonSchemaExtension implements GenerationConfig {
boolean useOptionalForGetters
boolean includeToString
String[] toStringExcludes
boolean excludeObjectHeaderFromToString
boolean initializeCollections
String outputEncoding
boolean parcelable
Expand Down Expand Up @@ -119,6 +120,7 @@ public class JsonSchemaExtension implements GenerationConfig {
includeAllPropertiesConstructor = true
includeToString = true
toStringExcludes = [] as String[]
excludeObjectHeaderFromToString = false
annotationStyle = AnnotationStyle.JACKSON
useTitleAsClassname = false
inclusionLevel = InclusionLevel.NON_NULL
Expand Down Expand Up @@ -249,6 +251,7 @@ public class JsonSchemaExtension implements GenerationConfig {
|includeCopyConstructor = ${includeCopyConstructor}
|includeToString = ${includeToString}
|toStringExcludes = ${Arrays.toString(toStringExcludes)}
|excludeObjectHeaderFromToString = ${excludeObjectHeaderFromToString}
|annotationStyle = ${annotationStyle.toString().toLowerCase()}
|useTitleAsClassname = ${useTitleAsClassname}
|inclusionLevel = ${InclusionLevel.toString() }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* Copyright © 2010-2020 Nokia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.jsonschema2pojo.integration.config;

import org.jsonschema2pojo.integration.util.Jsonschema2PojoRule;
import org.junit.Rule;
import org.junit.Test;

import java.lang.reflect.Method;
import java.util.Map;

import static org.jsonschema2pojo.integration.util.CodeGenerationHelper.config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

public class ExcludeToStringObjectHeaderIT {

@Rule
public Jsonschema2PojoRule schemaRule = new Jsonschema2PojoRule();

@SuppressWarnings({"unchecked", "rawtypes"})
private void testConfig(Map<String, Object> config, String expectedResultTemplate) throws ClassNotFoundException, SecurityException, NoSuchMethodException {
ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example", config);

Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

// throws NoSuchMethodException if method is not found
Method toString = generatedType.getDeclaredMethod("toString");
try {
Object primitiveProperties = generatedType.newInstance();
Object result = toString.invoke(primitiveProperties);
assertEquals(String.format(expectedResultTemplate, Integer.toHexString(System.identityHashCode(primitiveProperties))), result);
} catch (Exception e) {
fail("Unable to invoke toString method: " + e.getMessage());
}
}

@Test
public void beansExcludeObjectHeaderFromToString() throws ClassNotFoundException, SecurityException, NoSuchMethodException {
testConfig(config("excludeObjectHeaderFromToString", true),
"[a=<null>,b=<null>,c=<null>,additionalProperties={}]");
}

@Test
public void beansExcludeObjectHeaderFromToStringWithExcludes() throws ClassNotFoundException, SecurityException, NoSuchMethodException {
testConfig(config("excludeObjectHeaderFromToString", true, "toStringExcludes", new String[]{"b", "c"}),
"[a=<null>,additionalProperties={}]");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,14 @@ public class Jsonschema2PojoMojo extends AbstractMojo implements GenerationConfi
@Parameter(property = "jsonschema2pojo.toStringExcludes", defaultValue = "")
private String[] toStringExcludes = new String[] {};

/**
* Whether to include the object header in the generated toString implementation
*
* @since 1.2.1
*/
@Parameter(property = "jsonschema2pojo.excludeObjectHeaderFromToString", defaultValue = "false")
private boolean excludeObjectHeaderFromToString = false;

/**
* The style of annotations to use in the generated Java types.
* <p>
Expand Down Expand Up @@ -949,6 +957,9 @@ public String[] getToStringExcludes() {
return toStringExcludes;
}

@Override
public boolean isExcludeObjectHeaderFromToString() { return excludeObjectHeaderFromToString; }

@Override
public AnnotationStyle getAnnotationStyle() {
return AnnotationStyle.valueOf(annotationStyle.toUpperCase());
Expand Down

0 comments on commit f44d83e

Please sign in to comment.