Create a Java Annotation with IDE contextual behaviour

前端 未结 3 1570
Happy的楠姐
Happy的楠姐 2021-02-09 03:39

I\'ve created an Annotation

/**
 * Highlights this method is declared in XML
 */
public @interface FromXML {
}

I\'m using this on methods that

3条回答
  •  后悔当初
    2021-02-09 04:04

    I think you could create an interface defining this method. That way, your class will override the method and there should not be any warning.

    FromXML.java:

    public @interface FromXML {
    }
    

    MyInterface.java:

    public interface MyInterface {
        @FromXML
        public void onSomethingClick(View v);
    }
    

    MyClass.java

    public MyClass implements MyInterface {
    
        @Override
        @FromXML
        public void onSomethingClick(View v){
        }
    }
    

    EDIT : Another solution could be to define your method as abstract. Indeed, as I understand your code, your methods are just declaration (Implementations are in a XML file). So, your problem is more a design problem than an IDE problem (your IDE is just right about the warning). The reality is that your method is abstract and is defined somewhere else.

    Thus, defining your method as abstract will solve the problem but you'll have to make the class abstract:

    public abstract class MyClassUsingOnSomethingClick {
    
    /*
     * All the class implementation can be here as the normal class.
     */
    
        @FromXML
        public abstract void onSomethingClick(View v);
    
    }
    

    I know you'll say that this solution make it impossible to create object easily but you'll have two solutions then:

    1 - Create your objects inline:

    MyClassUsingOnSomethingClick a = new MyClassUsingOnSomethingClick() {
        @Override
        @FromXML
        public void onSomethingClick(View v) {}
    };
    

    2 - Create a factory method in your abstract MyClassUsingOnSomethingClick:

    public static final MyClassUsingOnSomethingClick createEmptyMyClassUsingOnSomethingClick() {
        return new MyClassUsingOnSomethingClick() {
            @Override
            @FromXML
            public void onSomethingClick(View v) {}
        };
    }
    
    // and then, create with: :
    MyClassUsingOnSomethingClick a = MyClassUsingOnSomethingClick.createEmptyMyClassUsingOnSomethingClick();
    

    Even is I understand that you would prefer a faster solution, I believe that this solution is the cleanest because:

    1. It respects the Object Oriented Programming philosophy.
    2. It is not specific to an IDE.
    3. It avoids Annotation Processing Tool (which, in my opinion should be used very wisely)

提交回复
热议问题