Dean Winchester
Dean Winchester

Reputation: 659

AspectJ - is there a way to 'hack' a static final field?

Say I have private final static int N = 1 in class A

Is there any chance to 'hack' so that N becomes 2(without touching the source file A.java)?

The set pointcut seems not work on these final fields.

The thing is, I have the source code of some project, and I'm making some modifications to it to deploy it in our region. I'm trying to make these changes without touching the source file unless I have to.

@VinceEmigh reflection wouldn't work in my case. The source code looks like:

class MyClass
  private final static String[] NAMES = {"Name1", "Name2", "Name3"};

  public void createIsland() {
      //something
      int i = getNumberOfIsland();
      String name = NAMES[i];
      createIslandWithName(name);
      //something
  }
end

The thing is I need to change those hard coded NAMES to something else

Upvotes: 1

Views: 1068

Answers (1)

kriegaex
kriegaex

Reputation: 67457

Sample driver class:

package de.scrum_master.app;

public class Application {
    private final static String[] NAMES = { "Name1", "Name2", "Name3" };

    public static void main(String[] args) {
        for (String name : NAMES)
            System.out.println(name);
    }
}

Aspect:

package de.scrum_master.aspect;

import de.scrum_master.app.Application;

public aspect ConstantChanger {
    Object around() : get(* Application.NAMES) {
        System.out.println(thisJoinPointStaticPart);
        return new String[] { "Hack1", "Hack2", "Hack3", "Hack4", "Hack5" };
    }
}

Output:

get(String[] de.scrum_master.app.Application.NAMES)
Hack1
Hack2
Hack3
Hack4
Hack5

This way you change the array size as well as its content. Is that what you need?

Upvotes: 4

Related Questions