Java中的C ++模板?
我想要这样的东西:
public abstract class ListenerEx<LISTENER, PARENT> implements LISTENER {
PARENT parent;
public ListenerEx(PARENT p) {
parent = p;
}
}
但它没有编译。有更好的解决方案吗?
像C ++模板这样的Java有什么东西可以在模板扣除后检查语法吗?
以下解释了为什么我需要这样一个ListenerEX类,
如果你已经知道它是什么,你不需要阅读以下内容。
我有一个主窗口,上面有一个按钮,我希望能够访问监听器中主窗口的某些方法:
public class MainWindow extends JFrame {
public void doSomething() {
/* ... */
}
public void doSomethingElse() {
/* ... */
}
private JButton button;
public MainWindow() {
button = new JButton(...);
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doSomething();
doSomethingElse();
}
});
}
}
这会编译但不能始终正常工作。
(当ActionListener没有doSomething()方法时,为什么会编译?)
我们当然可以这样做:
public class MainWindow extends JFrame {
public void doSomething() {
}
public void doSomethingElse() {
}
private JButton button;
public MainWindow() {
button = new JButton(...);
add(button);
class ActionListener1 implements ActionListener {
MainWindow parent;
public ActionListener(MainWindow p) {
parent = p;
}
public void actionPerformed(ActionEvent e) {
parent.doSomething();
parent.doSomethingElse();
}
}
button.addActionListener(new ActionListener1(this));
}
}
不过我讨厌这种风格......
所以我尝试过:
public abstract class ActionListenerEx<P> implements ActionListener {
P parent;
public ActionListenerEx(P p) {
parent = p;
}
}
public class MainWindow extends JFrame {
public void doSomething() {
}
public void doSomethingElse() {
}
private JButton button;
public MainWindow() {
button = new JButton(...);
add(button);
button.addActionListener(new ActionListenerEx<MainWindow>(this) {
public void actionPerformed(ActionEvent e) {
parent.doSomething();
parent.doSomethingElse();
}
});
}
}
但ActionListener旁边有很多听众......
public abstract class ActionListenerEx<LISTENER, PARENT> implements LISTENER {
PARENT parent;
public ActionListenerEx(PARENT p) {
parent = p;
}
}
但是,它不会编译......
我对Java很新鲜,我想知道是否有更好的解决方案。
没有找到相关结果
已邀请:
3 个回复
辰炔诚薯
。 你的第一个版本出了什么问题?看起来很好。除此之外,你的问题是什么?你到处都是,发布了一堆代码。
凄嘛姥
} 但它没有编译。有更好的解决方案吗?像C ++模板这样的Java有什么东西可以在模板扣除后检查语法吗? 它不能编译,因为你不能用硬编码的类/接口进行参数化。 所以,
毫无意义。你想要的是什么
呃...所以不习惯在stackoverflow上发帖
诫商