简体   繁体   English

使用自定义注释从抽象类中调用特定的子方法

[英]Calling particular child method from abstract class using custom annotation

I have a abstract class containing run() method and few children classes overriding run method with different implementation. 我有一个包含run()方法的抽象类,并覆盖了具有不同实现的run方法的几个子类。 There a custom annotation class also, each child class has this annotation with different value to distinguish each child class. 还有一个自定义注释类,每个子类都具有带有不同值的注释,以区分每个子类。 I was to call this run method for each child class from abstract class object using these annotations without using child class name. 我要使用这些注释为抽象类对象中的每个子类调用此run方法,而不使用子类名称。 Is it possible or there some other way to do this? 有可能还是有其他方法可以做到这一点?

CODE IS HERE------- 代码在这里-------

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CustomAnno {
    public String name();
}

public abstract class AbstractClass {

    abstract void run();

}

@CustomAnno(name="one")
public class ExtendingClassOne extends AbstractClass {

    @Override
    void run() {
        System.out.println("class one extending");

    }

}

@CustomAnno(name="two")
public class ExtendingClassTwo extends AbstractClass {

    @Override
    void run() {
        System.out.println("class two extending");

    }

}

So having abstract class and annotation values "one" and "two", can I call run method for each child class without using child class name. 因此,具有抽象类和注释值“一个”和“两个”,我可以为每个子类调用run方法,而无需使用子类名。

We can use ClassPathScanningCandidateComponentProvider spring library to list all the classes that use a particular kind of annotation. 我们可以使用ClassPathScanningCandidateComponentProvider弹簧库来列出所有使用特殊注释类型的类。 Here annotations can be custom or default one. 在这里,注释可以是自定义的,也可以是默认的。 So putting annotations on all child classes that extend that abstract class can give list of only those child classes only. 因此,在扩展该抽象类的所有子类上添加注释只能给出这些子类的列表。 This solved my problem. 这解决了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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