Posts tagged ‘delegate’

This blog is a contitunation of my previous entry (polish only sorry) in which I presented a solution for hiding certain operations on a collection using jdk’s dynamic proxy mechanism. It consited of MethodInterceptr which checked if specific method was called and in such a case it reported and error using RuntimeException.

With this entry I’d like to present a different approach using google collection ForwardingObjects. It’s parent for all types of wrappers – one for each collection type and the advantage of using wrapper is that hey’re all designed as abstract classes implementing interface for given type of Collection, in case of Set it’s ForwardingSet (to continue older example) and the only thing you need to do as implementor is to telli wrapper how it can find its delegate by providing a delegate method.

Below you can find previous example rewritten to use ForwardingSet with disabled clear method. Last but not least – this version is waaay much cleaner ­čÖé and you also let compiler do its job – if you check the previous post you’ll notice that there are two versions of this solution. The original one contained a but because I made a typo and the code checks for call to clean method instead of clear…

import java.util.Set;

class StructElement3 {

	private class ForwardingSetNoClear extends ForwardingSet<String> {

		private Set<String> delegate;
		public ForwardingSetNoClear(Set<String> delegate) {
			this.delegate = delegate;

		protected Set<String> delegate() {
			return delegate;

		public void clear() {
			throw new UnsupportedOperationException("Cannot call clear");

	public StructElement3(Set<String> obj) {
		Set<String> forwardingSet =  new ForwardingSetNoClear(obj);

		// yeah yeah keep talking...