Closures With Methods Examples - UnquietCode/Closures-for-Java GitHub Wiki

	public void methodCallingExample() {
		// Call a method from within the closure.

		String string = "The way I used to be";
		Closure1<String, String> closure = new AbstractClosure1<String,String>(string) {

			public String run(String a1) {
				return modify(a1) + ".";    // If it's visible to the closure, it can be run.
			}
		};

		out(string);
		out("\nis not the same as\n");
		out(closure.run(string));
	}

	  // (used by methodCallingTest)
	  private String modify(String input) {
	  	  return input.substring(0, 10).replace("T", "t") + "am";
	  }


	public void helperMethods() {
		// Because these are anonymous classes, you can add in whatever methods you want.
		// They will not be accessible outside of the closure (without reflection, of course).

		Closure theDestroyer = new AbstractClosure() {
			Random gen = new Random();

			public Object run(Object...args) {
				String string = (String) args[0];
				StringBuilder sb = new StringBuilder();

				for (int i=0; i < string.length(); ++i) {
					if (Character.isWhitespace(string.charAt(i)))
						sb.append(string.charAt(i));
					else
						sb.append(randomLetter(string));
				}

				return sb.toString();
			}

			// This method is accessible only within the closure.
			private char randomLetter(String string) {
				char c = '.';

				while (!Character.isLetter(c)) {
					c = string.charAt(gen.nextInt(string.length()));
				}

				return c;
			}
		};

		String theString = "The original string.";
		out(theString);
		out("\n\t\t!=\n");
		out(theDestroyer.run(theString));
	}