仅适用于某些类的接口?

发布于 2024-08-03 04:11:01 字数 194 浏览 6 评论 0原文

你能创建一个只能应用于某些类和子类的接口吗?

如果我的接口添加到JComponent的不同子类中,并且我需要引用JComponent和我的接口的方法...我应该怎么做?我可以通过将 JComponent 中的方法添加到我的界面来完成此任务。

这看起来很笨拙。有什么更好的方法来做到这一点?

Can you create an interface which can only be applied to certain classes and subclasses?

If my interface is only added to different subclasses of JComponent, and I need to refer to both the methods of JComponent and my interface... how should I do this? Off the top of my head I can accomplish this by adding methods from JComponent to my interface.

This seems clumsy. What is a better way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

偏闹i 2024-08-10 04:11:01

显而易见的解决方案是向接口添加一个返回组件的方法(可能是 this)。

JComponent getComponent();

或者甚至通用化你的界面:

 public interface MyInterface<C extends JComponent> {
     C getComponent();
     [...]
 }

这不是很好的设计,但它应该可以工作。

The obvious solution is to add a method to your interface that returns the component (which may be this).

JComponent getComponent();

Or even genericise your interface:

 public interface MyInterface<C extends JComponent> {
     C getComponent();
     [...]
 }

It's not great design, but it should work.

狼性发作 2024-08-10 04:11:01

在某些情况下,这可能不起作用,但使用泛型可以让您指定多种类型:

interface Foo { void frobulize(); }

class Bar {
    <T extends JComponent & Foo> String doFoo(T obj){
        obj.frobulize();
        return obj.getToolTipText();
    }
}

如果您希望对象作为非参数化类型上的字段,则可以将类型参数添加到构造函数(这是一个鲜为人知的功能,它绑定了迷惑并给你的同事留下深刻印象):

class Quux {
    private final Foo foo;
    private final JComponent component;
    public <T extends JComponent & Foo> Quux(T fc){
        foo = fc;
        component = fc;
    }
}

There might be scenarios where this won't work, but using generics lets you specify several types:

interface Foo { void frobulize(); }

class Bar {
    <T extends JComponent & Foo> String doFoo(T obj){
        obj.frobulize();
        return obj.getToolTipText();
    }
}

If you want the objects as fields on a non-parametrized type, you add type parameters to the constructor (a little-known feature which is bound to confuse and impress your colleagues):

class Quux {
    private final Foo foo;
    private final JComponent component;
    public <T extends JComponent & Foo> Quux(T fc){
        foo = fc;
        component = fc;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文