简体   繁体   中英

Is there a way to specify the interface/class being overrode using Java's Override annotation?

Some classes have many interfaces that they inherit from.

I want to make it explicit in my overrided methods what interface or class my method overrides so that when I look back at my code a month from now, I don't have to do a linear search over every interface being implemented and class being extended to find which interface or class the method is being overrode for.

Situation:

class Foo extends Bar implements Foo1, Foo2, Bar1, Bar2
{
    public Foo(){}

    @Override
    void foo1() {}

    @Override
    void foo2() {}

    @Override
    void bar1() {}

    @Override
    void bar2() {}
}

I want to do something like:

class Foo extends Bar implements Foo1, Foo2, Bar1, Bar2
{
    public Foo(){}

    @Overrides(source="Foo2")
    void foo1() {}

    @Overrides(source="Bar1")
    void foo2() {}

    @Overrides(source="Bar2")
    void bar1() {}

    @Overrides(source="Foo1")
    void bar2() {}
}

Is there a way to accomplish this?

Solution (thanks Nikem):

Can create a custom annotation (Overrides.java)

public @interface Overrides 
{
    String source() default ""; 
}

Override annotation is just a marker and compile time check to mark that -something- is being overridden without a care for where the method being overridden comes from. As user2357112 said, many IDEs can show you the interface/superclass a method comes from. If you need to have an IDE independent way to accomplish this then add a comment or javadocs saying which interface it comes from.

You can create your own annotation specifically for this purpose. Standard @Override annotation does not allow this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM