Shevek (shevek) wrote,

Hidden in the Java Language Spec, section 4.4 is a rarely used trick: Type parameters can have additional type bounds.

We all know List<String> and most of us know List<? extends Number>

Before I go on, please let me make quite clear that using multiple type bounds is always a mistake. Convince yourself firmly of that before you even go on. If you ever find yourself using one, you've done something wrong. Now, I can offer you

List<? extends Number & Runnable>

The first must be a class; the latter interfaces. Otherwise, it could either be reduced trivially to a single class, or proven never to exist. I tried using it once and decided it was a mistake, but this post was inspired by the following utility method (note this is private, so the screwed-up nature of multiple type bounds does not leak into an API):

private <T extends JComponent & MyInterface> void add(T object) {
// render object using JComponent interface
// invoke object using MyInterface

Of course, having said that the dual type bound is wrong, the traditional way to solve this would be to make a third Provider/Factory interface which provides both the component and the handler, and the implementation of the third interface may well return "this" for both cases, as do things like DefaultTableCellRenderer. But sometimes it's still neat.

Still wrong, though.

  • (no subject)

    I have yet to read a Java vs python comparison which was written by anyone with any serious enterprise development experience. If enterprises were…

  • (no subject)

    Today I was browsing my screenshots, and I found that I had failed the UK citizenship test. I took it again, just for fun, and failed with flying…

  • (no subject)

    Nobody in the USA has heard of Flanders and Swann. If the country had an editor, I would write to him to express my unmitigated disgust.

  • Post a new comment


    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 1 comment