Re: The D Programming Language
On 2006-12-13 23:48, Andrei Alexandrescu (See Website For Email) wrote:
Niklas Matthies wrote:
Well, it depends what one considers "basic". It's possible in Java to
have the statement
System.out.println("Hello, world!");
output "Suprise!" (or any other arbitrary string), by appropriate
preceding code.
(This is because string literals within a class are guaranteed to be
shared, so a different occurrence of "Hello, world!" in the source
code can be used to manipulate the contents of that shared String
object.)
I didn't know that! How is it possible?
Because string objects initialized from string literals are just
regular instances of the java.lang.String class, which is implemented
in plain Java (with the exception of its intern() method).
Got code?
Here you go:
class Test
{
public static void main(String[] args) throws Exception
{
java.util.HashSet set = new java.util.HashSet();
set.add("Hello, World!");
doEvil();
set.add("Hello, World!");
System.out.println(set); // prints "[Surprise!, Surprise!]"
}
static void doEvil() throws Exception
{
String s = "Surprise!";
String hw = "Hello, World!";
setField(hw, "value", s.toCharArray());
setField(hw, "count", Integer.valueOf(s.length()));
setField(hw, "hash", Integer.valueOf(0));
}
static void setField(Object object, String name, Object value)
throws Exception
{
java.lang.reflect.Field
field = object.getClass().getDeclaredField(name);
field.setAccessible(true);
field.set(object, value);
}
}
:)
-- Niklas Matthies
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]