You could so something like this. You would still have to have some overloaded methods to handle different argument counts and types but it wouldn't have to be a full delegation. This is just a simple example. It could be worked into a class. EDIT: Modified to handle most methods.
interface TriConsumer<T,R,S> {
public void accept(T t, R r, S s);
}
public class StringBuilderSol {
static int size = 20;
static StringBuilder sb = new StringBuilder(size);
public static void main(String[] args) {
execute(sb::append, "This is fun!");
System.out.println(sb);
execute(sb::append, "Java!");
System.out.println(sb);
execute(sb::delete, 0,3);
execute(sb::replace,0,1,"I");
execute(sb::insert, 1, " like ");
execute(sb::delete, 7,15);
System.out.println(sb);
execute(sb::append, "time to crash");
}
public static <T> void execute(Consumer<T> con,
T v) {
con.accept(v);
checkLength();
}
public static <T,R> void execute(
BiConsumer<T, R> biCon,
T index, R val) {
biCon.accept(index, val);
checkLength();
}
public static <T,R,S> void execute(
TriConsumer<T, R, S> triCon,
T index, R arg1, S arg2) {
triCon.accept(index, arg1, arg2);
checkLength();
}
public static void checkLength() {
if (sb.length() > size) {
throw new IndexOutOfBoundsException();
}
}
}
Prints
This is fun!
This is fun!Java!
I like Java!
Exception in thread "main" java.lang.IndexOutOfBoundsException
at stackOverflow.StringBuilderSol.checkLength(StringBuilderSol.java:50)
at stackOverflow.StringBuilderSol.execute(StringBuilderSol.java:32)
at stackOverflow.StringBuilderSol.main(StringBuilderSol.java:25)
Another option (but one that has its own problems) is to set up a timer to periodically check the size of the StringBuilder.