Skip to content

Instantly share code, notes, and snippets.

@SergeStinckwich
Created March 8, 2013 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SergeStinckwich/5118428 to your computer and use it in GitHub Desktop.
Save SergeStinckwich/5118428 to your computer and use it in GitHub Desktop.
import java.lang.reflect.*;
import java.beans.*;
public class FluentInterface<T> implements InvocationHandler {
Object obj;
public FluentInterface(Object obj) {
this.obj = obj;
}
public static <T> T create(Object object, Class fluentInterfaceClass) {
FluentInterface handler = new FluentInterface(object);
@SuppressWarnings("unchecked")
T fluentInterface = (T) Proxy.newProxyInstance(
fluentInterfaceClass.getClassLoader(),
new Class[]{fluentInterfaceClass},
handler);
return fluentInterface;
}
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
try {
String name = m.getName();
if ("create".equals(name)) {
return obj;
} else {
String setter = "set" + name.substring(0, 1).toUpperCase()
+ name.substring(1);
Statement stmt = new Statement(this.obj, setter, args);
stmt.execute();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return proxy;
}
}
public class Person {
private String firstName;
private String lastName;
private int age;
public static PersonFluentInterface with() {
return FluentInterface.create(
new Person(), PersonFluentInterface.class);
}
public Person() {
}
public void setAge(int age){
this.age = age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public String toString(){
return "Person("+firstName+", "+lastName+", "+age+")";
}
public static void main(String[] args) {
Person john = Person.with()
.firstName("John")
.lastName("Doe")
.age(30)
.create();
Person bob = Person.with()
.age(42)
.lastName("Black")
.firstName("Bob")
.create();
System.out.println(john);
System.out.println(bob);
}
}
public interface PersonFluentInterface {
public PersonFluentInterface firstName(String firstName);
public PersonFluentInterface lastName(String lastName);
public PersonFluentInterface age(int age);
public Person create();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment