0

我已经在这个问题中发布了一些相关代码: 动态指定返回数组列表的对象类型

现在我的问题更具体一点。

事实上,我正在使用以下“处理程序”类来调用实现接口的类的方法IMSSQLStatement

public class MSSQLHandler {

    IMSSQLStatement statement;

    public MSSQLHandler(IMSSQLStatement statement) {
        this.statement = statement;
    }

    public void invoke() throws SQLException {
        statement.executeStatement();
    }

    public List<?> getDataList() throws SQLException {
        return statement.getDataList();
    }
}

现在的问题是如何强制我(或实现我的接口的开发人员)将已实现类的创建对象放入MSSQLHandler

也许这是一个糟糕的设计,但我没有找到任何关于我的问题的信息和用例。

4

1 回答 1

1

是的,您可以使用带有显式构造函数的抽象类,它会在所有子类上自动调用:

public abstract class IMSSQLStatement {

    protected IMSSQLHandler handler;

    public IMSSQLStatement() {
        handler = new IMSSQLHandler(this);
    }
}

编辑:(参考评论)

If you want that only the handler should be able to call the methods in IMSSQLStatement, both classes should be placed in the same package. Allow only package-private and subclass access, by giving the protected modifier. Although the methods could be called in the subclass itself, it would not be accessible outside, with the exception of the package.

This won't solve your problem completely. The other (real bogus) way around would be reflection.

To use reflection, you should write in your documentation the exact method signature the subclass should use (of course, don't define an abstract method in the superclass), giving it the private modifier. The handler should access these methods through reflection.

Refer some document, that describes how to use reflection. This is complicated, and beyond the scope of SO.

于 2013-03-08T08:09:47.187 回答