Search code examples
javaaopaspectj

AspectJ: Access private fields?


I want to use an aspect to add getter and setter for a private id field. I know how to add a method through an aspect, but how can I access the private id field?

I thoght that I just have to make the aspect provileged. I tried the following code, but the aspect cannot access the id field.

public privileged aspect MyAspect {

public String Item.getId(){

    return this.id;
}

A possibility would be to user reflection like shown in this blog post: http://blog.m1key.me/2011/05/aop-aspectj-field-access-to-inejct.html

Is reflection the only possibility or is there a way to do it with AspectJ?


Solution

  • Are you sure you can't ? I just tested and it ran. Here's my full code:

    package com.example;
    
    public class ClassWithPrivate {
        private String s = "myStr";
    }
    
    ==========
    
    package com.example.aspect;
    
    import com.example.ClassWithPrivate;
    
    privileged public aspect AccessPrivate {
    
        public String ClassWithPrivate.getS() {
            return this.s;
        }
    
        public void ClassWithPrivate.setS(String str) {
            this.s = str;
        }
    }
    
    ==========
    
    package com.example;
    
    public class TestPrivate {
    
        public static void main(String[] args) {
    
            ClassWithPrivate test = new ClassWithPrivate();
            System.out.println(test.getS());
            test.setS("hello");
            System.out.println(test.getS());
        }
    }
    

    If for some reason, that does not work for you, you can use reflection, or another way as described here: https://web.archive.org/web/20161215045930/http://blogs.vmware.com/vfabric/2012/04/using-aspectj-for-accessing-private-members-without-reflection.html However, according to the benchmarks, it may not be worth it.