Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 876847
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T11:30:07+00:00 2026-05-15T11:30:07+00:00

Is there a way to automatically insert code into a method? I have the

  • 0

Is there a way to automatically insert code into a method?

I have the following typical field with a getter and setter and I would like to insert the indicated code into the setter method that records if the field was modified as well to insert the indicated “isFirstNameModified” field to also track if the field was modified or not.

 public class Person {

      Set<String> updatedFields = new LinkedHashSet<String>();

      String firstName;
      public String getFirstName(){
           return firstName;
      }

      boolean isFirstNameChanged = false;           // This code is inserted later
      public void setFirstName(String firstName){       
           if( !isFirstNameChanged ){               // This code is inserted later
                isFirstNameChanged = true;          // This code is inserted later
                updatedFields.add("firstName");     // This code is inserted later
           }                                        // This code is inserted later
           this.firstName = firstName;
      }
 }

I’m also not sure if I can the subset of the method name as a string from inside the method itself as indicated on the line where I add the fieldName as a string into the set of updated fields: updatedFields.add("firstName");. And I’m not sure how to insert fields into a class where I add the boolean field that tracks if the field has been modified or not before (for efficiency to prevent having to manipulate the Set): boolean isFirstNameChanged = false;

It seems to most obvious answer to this would be to use code templates inside eclipse, but I’m concerned about having to go back and change the code later.

Edit:::::::::

I Should have used this simpler code instead of the example above. All it does is add the name of the field as a string to a set.

 public class Person {

  Set<String> updatedFields = new LinkedHashSet<String>();

  String firstName;
  public String getFirstName(){
       return firstName;
  }
  public void setFirstName(String firstName){       
       updatedFields.add("firstName");        // This code is inserted later
       this.firstName = firstName;
  }

}

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T11:30:08+00:00Added an answer on May 15, 2026 at 11:30 am

    With AspectJ you can modify methods and fields with advises.

    My example is written with @AspectJ syntax which modifies the code at compile-time or load-time. If you want the modification at runtime, you can use Spring AOP which also supports this @AspectJ syntax.

    An example with a simple Person class and a stub repository. All information about which fields are updated is handled by an aspect called SetterAspect. It monitors which fields that are updated when the fields is written to.

    The other advice in this example is around the update method in the repository. This is to retrieve the data collected from the first aspect.

    The Person class:

    public class Person {
    
        private String firstName;
    
        private String lastName;
    
        public String getFirstName() {
            return firstName;
        }
    
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
    
        public String getLastName() {
            return lastName;
        }
    
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }   
    
        public static void main(String[] args) {
            Person person = new Person();
            person.setFirstName("James");
            person.lastName = "Jameson";
    
            DtoRepository<Person> personRepository = new DtoRepository<Person>();
            personRepository.update(person);
        }
    }
    

    The stub repository:

    public class DtoRepository<T> {
    
        public void update(T t) {
            System.out.println(t.getClass().getSimpleName() + " updated..");
        }
    
        public void updatePerson(T t, Set<String> updatedFields) {
            System.out.print("Updated the following fields on " +
                t.getClass().getSimpleName() + " in the repository: "
                + updatedFields);       
        }
    }
    

    The output for executing the main() method in the Person class with AspectJ:

    Updated the following fields on Person
    in the repository: [lastName,
    firstName]

    Important to note here is that the main() method calls on the DtoRepository.update(T t) but the DtoRepository.update(T t, Set<String> updatedFields) gets executed because of the around advice in the repository aspect.

    The aspect that monitors all writing to private fields in the demo package:

    @Aspect
    public class SetterAspect {
    
        private UpdatableDtoManager updatableDtoManager = 
            UpdatableDtoManager.INSTANCE;
    
        @Pointcut("set(private * demo.*.*)")
        public void setterMethod() {}
    
        @AfterReturning("setterMethod()")
        public void afterSetMethod(JoinPoint joinPoint) {
            String fieldName = joinPoint.getSignature().getName();
            updatableDtoManager.updateObjectWithUpdatedField(
                    fieldName, joinPoint.getTarget());      
        }
    }
    

    The repository aspect:

    @Aspect
    public class UpdatableDtoRepositoryAspect {
    
        private UpdatableDtoManager updatableDtoManager = 
            UpdatableDtoManager.INSTANCE;
    
        @Pointcut("execution(void demo.DtoRepository.update(*)) " +
                "&& args(object)")
        public void updateMethodInRepository(Object object) {}
    
        @Around("updateMethodInRepository(object)")
        public void aroundUpdateMethodInRepository(
                ProceedingJoinPoint joinPoint, Object object) {
    
            Set<String> updatedFields = 
                updatableDtoManager.getUpdatedFieldsForObject(object);
    
            if (updatedFields.size() > 0) {
                ((DtoRepository<Object>)joinPoint.getTarget()).
                    updatePerson(object, updatedFields);
            } else {
    
                // Returns without calling the repository.
                System.out.println("Nothing to update");
            }
        }   
    }
    

    Finally, the two helper classes used by the aspects:

    public enum UpdatableDtoManager {
    
        INSTANCE;
    
        private Map<Object, UpdatedObject> updatedObjects = 
            new HashMap<Object, UpdatedObject>();
    
        public void updateObjectWithUpdatedField(
                String fieldName, Object object) {
            if (!updatedObjects.containsKey(object)) {
                updatedObjects.put(object, new UpdatedObject());
            }
    
            UpdatedObject updatedObject = updatedObjects.get(object);
            if (!updatedObject.containsField(fieldName)) {
                updatedObject.add(fieldName);
            }
        }
    
        public Set<String> getUpdatedFieldsForObject(Object object) {
            UpdatedObject updatedObject = updatedObjects.get(object);
    
            final Set<String> updatedFields;
            if (updatedObject != null) {
                updatedFields = updatedObject.getUpdatedFields();
            } else {
                updatedFields = Collections.emptySet();
            }
    
            return updatedFields;
        }
    }
    

    and

    public class UpdatedObject {
    
        private Map<String, Object> updatedFields = 
            new HashMap<String, Object>();
    
        public boolean containsField(String fieldName) {
            return updatedFields.containsKey(fieldName);
        }
    
        public void add(String fieldName) {
            updatedFields.put(fieldName, fieldName);        
        }
    
        public Set<String> getUpdatedFields() {
            return Collections.unmodifiableSet(
                    updatedFields.keySet());
        }
    }
    

    My example does all the update logic with aspects. If all the DTOs implemented an interface that returns a Set<String>, you could have avoided the last aspect.

    I hope this answered your question!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 433k
  • Answers 433k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Done correctly it can be better for: the end user,… May 15, 2026 at 3:03 pm
  • Editorial Team
    Editorial Team added an answer Found the answer as soon as I posted the question.… May 15, 2026 at 3:03 pm
  • Editorial Team
    Editorial Team added an answer Are the clocks in sync on the two servers? May 15, 2026 at 3:03 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.