#

Sunday, January 30, 2011

Setter Chaining : Where it breaks

This is a section dedicated to keeping notes about the places where setter chaining breaks and how to work around (people welcome to contribute):

1. org.springframework.beans.BeanUtils.copyProperties(...); fails to set fields that do not support conventional bean setter methods.

Tuesday, January 11, 2011

Setter Chaining & generics

Although the concept of setter chaining is not new, thanks to a few good men I've picked the habit. However when using Inheritance, the setter of the base class returns type of "base class". This can disrupt the "coolness" of using chaining.

For the rest I'll let the code talk about the issue & a possible solution in more detail:


package com.arjun.misc;

/**
* "Setter chaining". The issue is that it returns the object of the
* type of the class in which the setter is.
* For Inheritance concepts this means if A<--B; then B.a()
* will return A not B (exclude overriding).
* This hardly helps chaining. Using generics to solve the problem
*
* @author Arjun Dhar | www.neurosys.biz
* */

public class GenericChainingSetters {
private static class A<T extends A> {
T setA(String something) {
return (T)this;
}
}

private static class B<T extends B> extends A<T> {
T setB(String something) {
return (T)this;
}
}

private static class C<T extends C> extends B<T> {
T setC(String something) {
return (T)this;
}
}

public static void main(String[] args) {
//WORKS
B<B> b = new B();
b.setA("abc").setB("abc again?!");

//WORKS
C<C> c = new C();
c.setA("abc").setB("abc again?!").setC("Hurray!");
}
}

Only thing is that as with Generics (erasure),
one cant (can but should not logically) do something stupid like:
B<C> b = new B();


Thoughts & suggestions welcome

thanks
-Arjun

Click here to see better way using Java 8