Inline object instantiation and transformation in Java

21,825

Solution 1

Yes but some people consider it hacky.

JFrame aFrame = new JFrame();
aFrame.add(new JPanel() {{
 setSize(100,100);
 setLocation(50,50);
 setBackground(Color.red);
}});

Basically you add another layer of {} (instance initialization block), which is executed when the panel is instantiated. therefore you can put any code in it. (like calling setters).

Solution 2

A nice trick is presented in @ClickerMonkey's answer. However, if a class supports method chaining, you can use a similar syntax without the initializer "hack":

new ChainClass().setSize(100,100) .setLocation(50,50) .setBackground(Color.red)

The drawback is that the ChainClass must look similar to this:

public class ChainClass  {
  public ChainClass setSize(int w, int h)  {
     // ...
     return this;
  }

  public ChainClass setLocation(int x, int y)  {
    // ...
    return this;
  }

  // etc.
}

This is, sadly, not the case for most standard Java classes. You can implement it for your classes though.

Share:
21,825
GCon
Author by

GCon

A flare for anything EE related. A Code perfectionist, git lover, SVN hater. Love me!

Updated on January 07, 2020

Comments

  • GCon
    GCon over 4 years

    I have come to Java from Visual Basic, and seem to think I have been, in many ways, spoiled :p

    Is there a way to instantiate an object and modify it inline? Something like:

    JFrame aFrame = new JFrame();   
    aFrame.add(new JPanel() {.setSize(100,100) .setLocation(50,50) .setBackground(Color.red) });
    

    I was able to @Override methods, but am looking for something simpler. I have search alot, but if there is a specific term for this kind of inline instantiation, it eludes me.

    Thank you for your time!

  • SJuan76
    SJuan76 over 12 years
    What is this technique called? I would like to know more about it.
  • alf
    alf over 12 years
    @SJuan76 it's called "anonymous class with an initializer"
  • Bhesh Gurung
    Bhesh Gurung over 12 years
    He is using a instance initialization block within the anonymous class, and calling it's inherited methods like this.setSize...
  • GCon
    GCon over 12 years
    Sir! You are a God! I knew it must exist, but I would never imagine using another pair of braces! As for "Anonymous class with an initializer", never would have even dreamed of it :p Thanks again!
  • Dave Newton
    Dave Newton over 12 years
    With the caveat that if something is looking for a specific class, they won't get it, as this "trick" creates an anonymous class each time it's used.
  • Jason Braucht
    Jason Braucht over 12 years
    Does anyone know of a compelling reason to do this instead of creating a local variable for the JPanel and calling the various set methods? Seems like this is seldom used syntax which is apt to cause some confusion when someone else reads it...?
  • Darius
    Darius over 11 years
    This is known as a Fluent interface. jQuery uses this technique.
  • Kent
    Kent almost 10 years
    That... is probably the most bug-prone piece of code I've ever seen. It will execute before the object is properly initialized.
  • Kent
    Kent almost 10 years
    That, right there, is why I want a "this" return type in java.
  • ClickerMonkey
    ClickerMonkey over 9 years
    That's not true at all... run the following code: pastebin.com/kLT1TweU. Maybe you should consider trying something instead of making assumptions about it.
  • ClickerMonkey
    ClickerMonkey over 6 years
    Especially because of generic classes... method chaining is annoying with generics when you have subclasses.
  • JRA_TLL
    JRA_TLL over 5 years
    That´s the Double Curly Braces Anti Pattern. See blog.jooq.org/2014/12/08/… "Every time you use double brace initialization god kills a kitten" - read the article, there are compelling reasons NOT TO USE THAT PATTERN!