简体   繁体   English

Java-N个被覆盖的抽象方法之一的强制继承

[英]Java - Force Inheritance of 1 of N Overridden Abstract Methods

Using Java 6, I have a situation where I want to force a child class to implement 1 of N overridden methods. 在使用Java 6的情况下,我想强制子类实现N个覆盖方法中的1个。 Let me explain with an example: 让我用一个例子来解释:

public abstract class TestClass {

  public abstract String isValidInput(ObjectOne objectOne);

  public abstract String isValidInput(ObjectOne objectOne, ObjectTwo objectTwo);

  public abstract String isValidInput(ObjectOne objectOne, ObjectTwo objectTwo, ObjectThree objectThree);

  //Lots of other Code

}

The problem I'm facing is that I do not know exactly how many objects or types of objects that I'm going to have to validate. 我面临的问题是我不知道要验证多少个对象或对象类型。 However, I do know that there is a limited number of possibilities. 但是,我确实知道,可能性有限。 (I used 3 in the example above but in reality it will likely be 5.) What I want to do is force my child class to implement only one of the isValidInput(...) methods depending on the situation. (我在上面的例子中使用3但在现实中它可能会是5)我想要做的就是逼我的子类只实现的一个 isValidInput(...)根据具体情况的方法。

What is the cleanest way to solve this problem? 解决此问题的最干净方法是什么?

Thank you very much for you time! 非常感谢您抽出宝贵的时间!

The only existing option in java is ellipsis (...) for a variable amount of arguments of the same type. Java中唯一存在的选项是省略号(...),表示可变数量的相同类型的参数。

For example: 例如:

public void doSomething(Object... arguments){
    // something
}

arguments is in that case a simple array. 在这种情况下,arguments是一个简单的数组。 Other options are probably rethinking the architecture. 其他选择可能正在重新考虑体系结构。 Which would be in my opinion the best option. 我认为这将是最佳选择。

Why not make it a composition of above answers with added generics ? 为什么不使用添加的泛型将其组成上述答案?

public interface Validator<T> {

    boolean validate(T... objects);
}

public class StringValidator implements Validator<String> {

    @Override
    public boolean validate(String... objects) {
        return false;
    }
}

I do not know exactly how many objects or types of objects 我不知道到底有多少个对象或对象类型

Then make all the objects you want to test, regardless of type, implement the same interface. 然后,使所有要测试的对象(无论类型如何)都实现相同的接口。 For example: 例如:

public interface Testable {
    public boolean isValid();
}

Then you can just pass a list of Testable objects: 然后,您可以传递可测试对象的列表:

public abstract class TestClass {
    public abstract String isValidInput(List<Testable> list);
}

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

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