简体   繁体   English

如何确保参数实现接口

[英]How to ensure an argument implements an interface

I'm working on a project where a have a list of classes that inherit from the abstract class Generator . 我正在一个项目中,该项目具有从抽象类Generator继承的类的列表。 It works kind of like a chain of responsibility , where each class gets instantiated after the other, calling a generate() method. 它的工作方式就像一条责任链 ,其中每个类都在另一个类之后实例化,并调用generate()方法。 The only special thing is that each Generator is passed to the next, so that the next is able to call some methods of the previous one as a way to ensure that it continuos its work taking the same assumptions. 唯一的特别之处在于,每个Generator都传递给下一个Generator ,以便下一个能够调用上一个Generator某些方法,以确保它以相同的假设继续进行其工作。

With this setup, I would like to allow each class on the chain to determine an interface that the previous one must implement, such that it knows which methods it has available. 通过这种设置,我希望允许链上的每个类确定前一个必须实现的接口,以便它知道可用的方法。

If the class does not implement such interface, simply an error will be shown (it's a command-line tool). 如果该类未实现此类接口,则将仅显示错误(它是命令行工具)。

I've been looking into several possibilities, but I don't really know how to perform a proper implementation of this. 我一直在研究几种可能性,但是我真的不知道如何正确地实现这一点。 Can you think of a way to do this at compile time? 您能想到在编译时执行此操作的方法吗? Would I need to do run-time checks like instanceof ? 我需要像instanceof一样进行运行时检查吗?

I leave here a bit of the skeleton representing what I have now, in case it helps. 如果有帮助,我在这里留下一些骨架来表示我现在拥有的东西。

public abstract class Generator {
    protected Generator(Object somePrivateStuff) {/* ... */}
    public abstract void generate();
}

public class SpecialGenerator extends Generator {
    protected SpecialGenerator(Object o) { super(o); }
    public void generate() {
        // Some actual implementation
    }
}

public class Main {
    public static void main(String[] args) {
        // Dynamically load all the classes extending Generator
        // via the Reflections library, and call the method generate()
        // on each one
    }
}

Any idea will be appreciated. 任何想法将不胜感激。 Thanks in advance. 提前致谢。

If you load classes dynamically, eg by String names, instanceof is useless because you don't know them at compile time. 如果您动态加载类(例如,按String名称),则instanceof是无用的,因为您在编译时不知道它们。 Instead, you should use Class#isAssignableFrom() : 相反,您应该使用Class#isAssignableFrom()

for (Class<?> clazz : loaded) {
    if (Generator.class.isAssignableFrom(clazz)) {
        // instantiate
    } else {
        // print error
    }
}

Without knowing how exactly instantiation should be performed, it is hard to suggest more detailed code. 在不知道应如何精确执行实例化的情况下,很难建议更详细的代码。

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

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