【问题标题】:Using methods with returned jcomponents and generics使用带有返回的 jcomponents 和泛型的方法
【发布时间】:2012-11-28 01:29:55
【问题描述】:

这是一个两部分的问题。首先,是否可以使用通用的定义对象方法,例如:

public class MyClass<T>{

    public MyClass(T t){
        t.setText("Hello World"); // Assume class T is JMenuIten has the special method setText
    }

}

此代码无法按原样运行,但显示了我的目标的总体思路。我想使用该封装对象特有的方法。但是,如果我要传入另一个对象,例如包含封装方法 .doSomething 的对象。我想做...

public class MyClass<T>{

    public MyClass(T t){
        t.doSomething("Hello World"); // Assume class T is JMenuIten has the special method setText
    }

}

我希望可以做到这一点,否则我将不得不编写多个构造函数来处理我所有的特殊情况。

我的第二个问题是类似的,我想返回一个 GUI 组件并执行一个语句,例如 ...

myJPanel.getComponent(1).setText("Hello"); // Assuming index 1 is a JLabel and setText is a specific method defined in the JLabel class

此代码不起作用,因为编译器无法提前告知运行时需要哪些符号,尽管我希望有一种方法可以使这样的事情起作用。我还想知道是否有一种方法可以告诉我 .getComponent() 正在返回的类类型(如果可能的话)。我正在尝试使代码尽可能动态,而不必对所有内容进行硬编码。

谢谢

【问题讨论】:

  • 那么像public class MyClass&lt;T extends JComponent&gt; { 这样的?
  • 哦,我以为 意味着只能使用 JComponent 泛型。我不明白它也允许我使用其中的方法。谢谢,这一切都清楚了!

标签: java swing oop generics jcomponent


【解决方案1】:

您必须使用有界通配符。

例如

public interface MyObject {
    void myMethod();
}

public class GenericObj<T extends MyObject> {
    private T t;

    public void invokeMethod() {
        t.myMethod(); //this way you can invoke methods (declcared in MyObject) on T
    }
}

【讨论】:

  • 谢谢,直到我需要有界通配符,我才明白它们的用途。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多