Carlos Melo
Carlos Melo

Reputation: 3152

How to declare an inter-type method with return type of every object's class?

In my AspectJ project, I have a code like the following:

public aspect MyAspect {
    public Object MyInterface.getMyself() {
        return this;
    }
}


public interface MyInterface {
}

public class MyClassOne implements MyInterface {}
public class MyClassTwo implements MyInterface {}

So, how does AspectJ inject the code within the inter-type declarations? Also, is there a way of, instead of declaring MyInterface.getMyself()'s as Object, declare as this.getClass() or anything like that, i.e., injecting MyClassOne and MyClassTwo where applicable?

Upvotes: 1

Views: 148

Answers (1)

Andrew Eisenberg
Andrew Eisenberg

Reputation: 28737

Try this:

aspect MyAspect {
    public S MyInterface<S>.getMyself() {
        return (S) this;
    }  
}

interface MyInterface<T extends MyInterface<T>> {
}

class MyClassOne implements MyInterface<MyClassOne> {}
class MyClassTwo implements MyInterface<MyClassTwo> {}

class Main {
    public static void main(String[] args) {
        MyClassOne aClassOne = new MyClassOne().getMyself();
        MyClassTwo aClassTwo = new MyClassTwo().getMyself();
        MyClassOne errorClassOne = new MyClassTwo().getMyself(); // compile error
        MyClassTwo errorClassTwo = new MyClassOne().getMyself(); // compile error
    }
}

Fun with generics! Answer is straight forward, I think, but let me know if this is confusing for you.

Upvotes: 1

Related Questions