Modify Eclipse's default toString template to automatically process sensitive fields

Source: Internet
Author: User
Tags locale win32 stringbuffer
Introduction:
Eclipse can generate the ToString method by default, but the auto-generated code sometimes doesn't meet the actual requirements, and here's a demonstration of how to change the auto-generated tostring method by modifying the eclipse source.

1. Target
1.1 Change the default toString template to
{${member.name ()}=${member.value}, ${othermembers}}
1.2 Code style is selected by default Stringbuilder/stringbuffer
1.3 Each field in the ToString method takes one row
Sensitive fields are automatically processed in the 1.4 toString method
# The revised screenshot is as follows:


2. Dependent jar
Eclipse_home\plugins\com.ibm.icu_50.1.1.v201304230130.jar
Eclipse_home\plugins\org.eclipse.core.commands_3.6.100.v20130515-1857.jar
Eclipse_home\plugins\org.eclipse.core.resources_3.8.101.v20130717-0806.jar
Eclipse_home\plugins\org.eclipse.core.runtime_3.9.100.v20131218-1515.jar
Eclipse_home\plugins\org.eclipse.equinox.common_3.6.200.v20130402-1505.jar
Eclipse_home\plugins\org.eclipse.jdt.core_3.9.2.v20140114-1555.jar
Eclipse_home\plugins\org.eclipse.jdt.ui_3.9.2.v20131106-1600.jar
Eclipse_home\plugins\org.eclipse.jface_3.9.1.v20130725-1141.jar
Eclipse_home\plugins\org.eclipse.swt.win32.win32.x86_3.102.1.v20140206-1358.jar
Eclipse_home\plugins\org.eclipse.ui.workbench_3.105.2.v20140211-1711.jar


3. Download Eclipse Source code
http://archive.eclipse.org/eclipse/downloads/

4. Files that need to be modified
4.1 Modifying the default template for ToString
Org.eclipse.jdt.internal.corext.codemanipulation.tostringgeneration.ToStringTemplateParser
Org.eclipse.jdt.internal.ui.dialogs.GenerateToStringDialog
# Generatetostringdialog file content does not need to be modified, just need to recompile

4.2 Code style is selected by default Stringbuilder/stringbuffer
Org.eclipse.jdt.internal.corext.codemanipulation.tostringgeneration.ToStringGenerationSettings

Sensitive fields are automatically processed in the 4.3 toString method
Org.eclipse.jdt.internal.corext.codemanipulation.tostringgeneration.StringBuilderGenerator

/******************************************************************************* * Copyright (c), Mateusz
 Matela and others. * All rights reserved. This program and the accompanying materials * is made available under the terms of the Eclipse public License v1.0 * WH      Ich accompanies this distribution, and are available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Mateusz Matela <mateusz.matela@gmail.com>-[Code manipulation] [DCR] toString () builder wizard-https://bugs. eclipse.org/bugs/show_bug.cgi?id=26070 ************************************************************************

/package org.eclipse.jdt.internal.corext.codemanipulation.tostringgeneration;
Import java.util.ArrayList;
Import java.util.List;

Import Java.util.Locale;
Import org.eclipse.core.runtime.CoreException;
Import org.eclipse.jdt.core.NamingConventions;
Import Org.eclipse.jdt.core.dom.ASTNode;
Import Org.eclipse.jdt.core.dom.Block; Import org.eclipse.jdt.cOre.dom.ClassInstanceCreation;
Import org.eclipse.jdt.core.dom.Expression;
Import org.eclipse.jdt.core.dom.IfStatement;
Import org.eclipse.jdt.core.dom.MethodInvocation;
Import Org.eclipse.jdt.core.dom.Name;
Import org.eclipse.jdt.core.dom.ReturnStatement;
Import org.eclipse.jdt.core.dom.Statement;
Import org.eclipse.jdt.core.dom.StringLiteral;
Import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
Import org.eclipse.jdt.core.dom.VariableDeclarationStatement;


Import Org.eclipse.jdt.core.dom.InfixExpression.Operator; /** * <p> * Implementation of <code>AbstractToStringGenerator</code> that creates <code>tostrin G () </code> * method using <code>StringBuilder</code> (or <code>StringBuffer</code> for Old versions of the JDK) * </p> * <p> * Generated methods look like this: * * <pre> * public String t
 Ostring () {* StringBuilder builder= new StringBuilder ();
 * Builder.append ("Fooclass (field1="); * BuilDer.append (field1);
 * Builder.append (", field2=");
 * Builder.append (FIELD2);
 * Builder.append (")");
 * return builder.tostring (); *} * </pre> * * </p> * * @since 3.5 */public class Stringbuildergenerator extends Abstracttostringge

	Nerator {protected StringBuffer fbuffer;

	protected String fbuildervariablename; Protected final String append_method_name= "APPEND"; $NON-nls-1$ protected void Flushbuffer (Block target) {if (fbuffer.length () > 0) {stringliteral literal= fAst
			. Newstringliteral ();
			Literal.setliteralvalue (Fbuffer.tostring ());
			if (target = = null) target= tostringmethod.getbody (); Target.statements (). Add (Fast.newexpressionstatement (Createmethodinvocation (Fbuildervariablename, APPEND_METHOD_
			NAME, literal));
		Fbuffer.setlength (0);
		}} @Override protected void Initialize () {super.initialize (); Fbuildervariablename= createnamesuggestion (GetContext (). Is50orhigher ()? "SB": "SB", namingconventions.vk_local); //$NON-nls-1$//$NON-nls-2$ fbuffer= new StringBuffer ();
		Variabledeclarationfragment fragment= fast.newvariabledeclarationfragment ();
		Fragment.setname (Fast.newsimplename (fbuildervariablename));
		Classinstancecreation classinstance= fast.newclassinstancecreation (); Name typename= AddImport (GetContext (). Is50orhigher ()? "Java.lang.StringBuilder": "Java.lang.StringBuffer");
		$NON-nls-1$//$NON-nls-2$ Classinstance.settype (Fast.newsimpletype (typeName));
		Fragment.setinitializer (classinstance);
		Variabledeclarationstatement vstatement= fast.newvariabledeclarationstatement (fragment);
		Vstatement.settype (Fast.newsimpletype (Name) astnode.copysubtree (fAst, typeName));
	Tostringmethod.getbody (). Statements (). Add (Vstatement);
		} @Override protected void complete () throws coreexception {flushbuffer (null);
		Super.complete ();
		Returnstatement rstatement= fast.newreturnstatement (); Rstatement.setexpression (Createmethodinvocation (Fbuildervariablename, "toString", null)); $NOn-nls-1$ Tostringmethod.getbody (). Statements (). Add (Rstatement); } protected void AddElement (Object element, block block) {if (element instanceof String) fbuffer.append ((String) El
		Ement);
			if (element instanceof Expression) {flushbuffer (block); Block.statements (). Add (Fast.newexpressionstatement (Createmethodinvocation (Fbuildervariablename, APPEND_METHOD_
		NAME, (Expression) element)); }} @Override protected void Addmemberchecknull (Object member, Boolean addseparator) {ifstatement ifstatement= fAst
		. Newifstatement (); Ifstatement.setexpression (Createinfixexpression (Creatememberaccessexpression (member, True, true), operator.not_
		EQUALS, Fast.newnullliteral ()));
		Block thenblock= Fast.newblock ();
		Flushbuffer (NULL);
		String[] arraystring= getcontext (). Gettemplateparser (). GetBody ();
		for (int i= 0; i < arraystring.length; i++) {addelement (Processelement (Arraystring[i], member), Thenblock); } if (AddSeparator) addelement (GetContext (). GettemplateparseR (). Getseparator (), thenblock);

		Flushbuffer (Thenblock); if (thenblock.statements (). Size () = = 1 &&!getcontext (). Isforceblocks ()) {ifstatement.setthenstatement (
		Statement) Astnode.copysubtree (fAst, (Astnode) thenblock.statements (). Get (0)));
		} else {ifstatement.setthenstatement (thenblock);
	} tostringmethod.getbody (). Statements (). Add (Ifstatement);
	} @Override protected void AddElement (Object element) {addelement (element, Tostringmethod.getbody ()); ////////////////////The following is the newly added content///////////////////////////////** * Add member Information */@SuppressWarnings
        
        ("unchecked") protected void AddMember (Object member, Boolean addseparator) {flushbuffer (null);
        List<object> objlist = new arraylist<object> ();
        Object fieldName = null;
        Object fieldvalue = null;
        String templateelement = null;
        
        StringBuilder sb = new StringBuilder (); string[] Stringarray = this.fContext.geTtemplateparser (). GetBody ();
            for (int i = 0; i < stringarray.length; i++) {templateelement = Stringarray[i]; if (Templateelement.equals ("${member.name}") | | templateelement.equals ("${member.name ()}")) {FieldName =
                Processelement (Stringarray[i], member);
                Objlist.add (FieldName);
            Continue
                } else if (templateelement = = "${member.value}") {Fieldvalue = Processelement (Stringarray[i], member);
                if (Issensitivefield (FieldName)) {fieldvalue = "*******";
                } objlist.add (Fieldvalue);
            Continue
            } else {Objlist.add (processelement (Stringarray[i], member));
        }} if (AddSeparator) {Objlist.add (This.fContext.getTemplateParser (). Getseparator ());
        } Expression currexpression = null; for (Object element:objlist{if (element instanceof String) {sb.append (element); } else if (element instanceof Expression) {if (Sb.length ()! = 0) {stringliteral Lite
                    RAL = This.fAst.newStringLiteral ();
                    Literal.setliteralvalue (Sb.tostring ());
                    Currexpression = Getnextexpression (currexpression, literal);
                Sb.delete (0, Sb.length ());
            } currexpression = Getnextexpression (Currexpression, (Expression) element);
            }} if (Sb.length ()! = 0) {stringliteral literal = this.fAst.newStringLiteral ();
            Literal.setliteralvalue (Sb.tostring ());
            Currexpression = Getnextexpression (currexpression, literal);
        Sb.delete (0, Sb.length ());
    } this.toStringMethod.getBody (). Statements (). Add (This.fAst.newExpressionStatement (currexpression)); }/** * Calculates a new expression * @paramCurrexpression * @param argument * @return * */@SuppressWarnings ("unchecked") Private Expression get Nextexpression (expression currexpression, expression argument) {methodinvocation invocation = This.fAst.newMethod
        Invocation ();
        if (currexpression = = null) {invocation.setexpression (This.fAst.newName (this.fbuildervariablename));
        } else {invocation.setexpression (currexpression);
        } invocation.setname (This.fAst.newSimpleName ("append"));
        Invocation.arguments (). Add (argument);
    return invocation;  }/** * Determines if a sensitive field * @param fieldName * @return */Private Boolean Issensitivefield (Object
        FieldName) {String name = string.valueof (fieldName). toLowerCase (locale.us);
        string[] words = new string[]{"Pass", "PWD", "session", "token"};
            for (String word:words) {if (Name.contains (word)) {return true; }
        } return false; }////////////////////End//////////////////////////////}
5. Replace the contents of the jar package with the compiled *.class file
Org.eclipse.jdt.ui_3.9.2.v20131106-1600.jar
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.