AspectJ: Access to private fields?

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

I want to say that I just need to make the aspect justified. I tried the following code, but this aspect cannot access the id field.

public privileged aspect MyAspect {

public String Item.getId(){

    return this.id;
}

Perhaps there would be a reflection of the user, as shown in this blog post: http://blog.m1key.me/2011/05/aop-aspectj-field-access-to-inejct.html

Is reflection the only option or is there a way to do this with AspectJ?

+3
source share
1 answer

Are you sure you can't? I just tested and he ran. Here is 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());
    }
}

- , , : http://blogs.vmware.com/vfabric/2012/04/using-aspectj-for-accessing-private-members-without-reflection.html , , .

+6

All Articles