Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AspectJ: Access private fields?

Tags:

java

aop

aspectj

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?

like image 841
punkyduck Avatar asked May 23 '12 13:05

punkyduck


People also ask

How to access a private field in Java?

If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.

Is AspectJ a framework?

In this article, we'll look at answering these questions and introduce Spring AOP and AspectJ – the two most popular AOP frameworks for Java.


1 Answers

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.

like image 182
anjosc Avatar answered Sep 28 '22 03:09

anjosc