Passing this as a method

Controlp5 passes this as a method,
controlP5 = new ControlP5(this)

How do you create a class that can do this?

1 Like
import processing.core.PApplet;

public class Library {
  protected final PApplet p;

  public Library(final PApplet pa) {
    p = pa;
  }
}
2 Likes

Does this allow you to retrieve all sketch events and variables? What are the limitations?

It’s restricted to PApplet’s members only: :disappointed:
Processing.GitHub.io/processing-javadocs/core/processing/core/PApplet.html

Beyond that, you’re gonna need to rely on reflection/inspection techniques: :grimacing:
Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/reflect/package-summary.html

2 Likes

‚this‘ is a keyword refering to the instance of the object. It not only works with PApplet, but you can also do something like this :

class Test {
   float a = 0;

   Test () {

   }

   void setA( float a) {
      this.a = a; // in this case ‚this‘ is used to differentiate between the classes variable ‚a’ and the methods parameter ‚a‘
// Generally you don‘t need this in Processing, because it is implied, but there can be moments when you need it. 
   }

   //But you could also do something nonsensical like this
   Test getThis() {
      return this; //that makes no sense, because you‘d need a reference to this objects instance 
// to even call this method that just returns a reference to this Objects instance
// but maybe there might be a use for that...
   }

}

Generally ‚this‘ is a reference to the instance of the class it is called within.

In your case, it is called within the PApplet, and thus gives back a reference to your current PApplet, so that controlP5 can reference it.

It‘s often needed if you have to communicate with external classes.

2 Likes

Returning this (the object self-reference) is actually common to do in method chaining – e.g. in fluent interfaces.

So:

/**
 * Method chaining example
 * 2019-12 Jeremy Douglass -- Processing 3.4
 */
class Test {
  Test be(){
    print("be ");
    return this;
  }
  Test go(){
    print("go ");
    return this;
  }
  Test say(String s){
    print(s);
    return this;
  }
}

Test t = new Test();
t.go().be().say("done!");
// go be done!
3 Likes

Ohhh, that is awesome :sweat_smile:

I didn‘t know that was a thing, though thinking about it now, it sure makes sense :sweat_smile:

Thanks :blush: