Note that there are some explanatory texts on larger screens.

plurals
  1. POC++Template in Java?
    text
    copied!<p>I want something like this:</p> <pre><code>public abstract class ListenerEx&lt;LISTENER, PARENT&gt; implements LISTENER { PARENT parent; public ListenerEx(PARENT p) { parent = p; } } </code></pre> <p>But it doesn't compile. Is there a better solution? Is there something in Java like C++ template that would do check syntax after template deduction?</p> <hr> <p>The following explains why I need such a ListenerEX class, if you already know what it is, you don't need to read the following.</p> <p>I have a main window, and a button on it, and I want to get access to some method of the main window's within the listener:</p> <pre><code>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(); } }); } } </code></pre> <p>This would compile but does not work properly all the time. (Why would it compile when the ActionListener does not have doSomething() method?)</p> <p>Of course we can do it like this:</p> <pre><code>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)); } } </code></pre> <p>However I hate this style ...</p> <p>So I tried:</p> <pre><code>public abstract class ActionListenerEx&lt;P&gt; 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&lt;MainWindow&gt;(this) { public void actionPerformed(ActionEvent e) { parent.doSomething(); parent.doSomethingElse(); } }); } } </code></pre> <p>But there's lots of Listeners beside the ActionListener ...</p> <pre><code>public abstract class ActionListenerEx&lt;LISTENER, PARENT&gt; implements LISTENER { PARENT parent; public ActionListenerEx(PARENT p) { parent = p; } } </code></pre> <p>However, it won't compile ...</p> <p>I am fresh at Java, and I wonder if there's already better solution.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload