Showing posts with label tips. Show all posts
Showing posts with label tips. Show all posts

Sunday, April 3, 2011

XML escaping

Did you ever want to define a constant in your code containing an XML string? For instance in a unit test to test if you can transform a piece of XML via XSLT into some desired format? You can do this the hard or the easy way: Either you take the chunk of XML, copy it in your IDE or some text editor and replace all double quotes with \" to escape them. Then you can start adding carriage returns in the String to have a somewhat readable piece of text. In case your XML contains all streets in Belgium, you will feel very, very useful doing this.

Or, you can have your IDE doing the work for you. In eclipse simply go to 'Window>Preference>Java>Editor>Typing' and check the “Escape text when pasting into a string literal“ option. As you can see it also adds the newlines and carriage returns:




I remember thinking 'Damn, I wish I knew about this before' when I first discovered this option. That might just be the criterium for any useful IDE feature I guess.

Wednesday, June 9, 2010

There can be only one

Before Java release 1.5 you had to do the following to create a Singleton:

public class ImASingleton {

private static final ImASingleton INSTANCE = new ImASingleton();

private ImASingleton() {
}

public static ImASingleton getInstance() {
return INSTANCE;
}
}

And to be able to serialize this singleton, you had to do 3 things:
1. Implement the Serializable interface.
2. Mark the instance fields transient if you didn't want them to be serialized.
3. Define a readResolve() method to return the single instance. This is a hook method called in the deserialization process. If you don't provide this method, the default implementation will always create a new instance in stead of your unique instance!

public class ImASingleton implements Serializable {

private static final ImASingleton INSTANCE = new ImASingleton();
private final transient Object nonSerializableField;

private ImASingleton() {
}

public static ImASingleton getInstance() {
return INSTANCE;
}

private Object readResolve() {
return INSTANCE;
}
}

As of Java 1.5 the preferred way to create a singleton is simply by using an enum. This get's you the Serialization for free.


public enum MySingleton() {
INSTANCE;
}