Hacking Into A Java Class

Umar Ashfaq
Eastros
Published in
1 min readMay 29, 2013

Official Java Docs may call it Anonymous Inner Classes or name it with some other heavy-weight formal jargon, but I would like to call it hacking into a Java class because with this technique you can inject your code into an existing class method.

For example, if you have a message queue and you want to make sure that you email the message items when at least 20 items have been accumulated in the queue, you can try this technique:
[sourcecode language=”java”]
Queue<String> queue = new LinkedList<String>() {
@Override
public boolean add(String e) {
// save the result from original functionality
boolean result = super.add(e);

// inject our functionality
if ( this.size() >= 20 ) {
String str;
StringBuilder grandString = new StringBuilder();
while ( ( str = this.poll() ) != null ) {
grandString.append(str)
.append(“\n”);
}

// log or grandString or email to a recipient
System.out.println(grandString);
}
// return original result
return result;
}
};
[/sourcecode]
Cool, isn’t it?

--

--