Simulating reference with wrappers.
One way you can have this behavior somehow simulated is create a generic wrapper.
public class _<E> {
E ref;
public _( E e ){
ref = e;
}
public E g() { return ref; }
public void s( E e ){ this.ref = e; }
public String toString() {
return ref.toString();
}
}
I'm not too convinced about the value of this code, by I couldn't help it, I had to code it :)
So here it is.
The sample usage:
public class Test {
public static void main ( String [] args ) {
_<Integer> iByRef = new _<Integer>( 1 );
addOne( iByRef );
System.out.println( iByRef ); // prints 2
_<String> sByRef = new _<String>( "Hola" );
reverse( sByRef );
System.out.println( sByRef ); // prints aloH
}
// Change the value of ref by adding 1
public static void addOne( _<Integer> ref ) {
int i = ref.g();
ref.s( ++i );
// or
//int i = ref.g();
//ref.s( i + 1 );
}
// Reverse the vale of a string.
public static void reverse( _<String> otherRef ) {
String v = otherRef.g();
String reversed = new StringBuilder( v ).reverse().toString();
otherRef.s( reversed );
}
}
The amusing thing here, is the generic wrapper class name is "_" which is a valid class identifier. So a declaration reads:
For an integer:
_<Integer> iByRef = new _<Integer>( 1 );
For a String:
_<String> sByRef = new _<String>( "Hola" );
For any other class
_<Employee> employee = new _<Employee>( Employee.byId(123) );
The methods "s" and "g" stands for set and get :P