Question

I will illustrate my question with the below posted code. It was created specifically for this purpose. The fact that it uses inner interface and inner classes is immaterial (it was just a convenience). The code compiles and runs as expected.

In this code I use inheritance with the sole purpose to declare that a class implements an interface, so later on I can cast them up and use polymorphic behavior. Parent classes already have methods to comply with the interface, so no overriding is required.

Swing is used just as an example. Nothing there is conceptually Swing-specific.

import java.util.*;
import javax.swing.*;

public class TextComponent {

    // Borrowed from com.google.gwt.user.client.ui
    interface HasText {
        String getText();
        void setText(String text);
    }

    static class MyLabel extends JLabel implements HasText {

        public MyLabel() {
            super();
        }

        public MyLabel(String txt) {
            super(txt);     
        }
    }

    static class MyTextField extends JTextField implements HasText {

        public MyTextField() {
            super();
        }

        public MyTextField(String txt) {
            super(txt);
        }
    }

    public static void main(String[] args) {
        List<HasText> txtList = new ArrayList<>();
        txtList.add(new MyLabel("Label"));
        txtList.add(new MyTextField("Text Field"));

        for (HasText component : txtList) {
            System.out.println(component.getText());
        }

    }

}

It seems that the proper way to deal with such tasks (declare already implemented interface) is to either use dynamic proxies (as suggested in this SO post) or 3rd-party tools (such as javassist or CGLIB as pointed out here).

QUESTIONS:

  1. So, is there something in-between static inheritance (or composition) and dynamic reflection-based solutions?

  2. Have I missed something really simple?

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top