Archive for the ‘Java’ Category

Functional Languages

Sunday, April 6th, 2008

Disclaimer: I’m becoming enamored with Functional Languages of late, and Mathematica, Lisp and Scheme in particular. But, the projects I support are all written in Java.

So, I stumbled across the codemodel project today. https://codemodel.dev.java.net/ It looks to be just what you need if you want to generate code programmatically from java. It really looks pretty slick. I couldn’t find a way for it to parse existing code, but that’s beyond the scope of what they want to do. As I was scrolling through the 80+ classes I was struck by the cognitive effort it would require to get good at this tool. 80 classes is pretty small for an API, and I imagine with a few days of intense work one could get pretty adapt at it. The design is clean, the names are intuitive so really Kohsuke Kawaguchi’ has done a bang up job on the system, and this is not a rant on his skills which appear to be formidable. This is a rant on Java. This should just be built into the language. Seeing languages that build on and operate directly on the parse tree of the language has given me a huge appreciation for the power of those languages. To automatically build code in any of the afore mentioned languages, you just do it using the core language directly, building up the parse tree using language mechanisms. So, for instance, in Mathematica, if I want to create text to represent a function, I just munge the OutputForm of an expression. It’s no wonder Lispers foam at the mouth so profusely. This power comes “for free” with the language definition. It’s just astonishing!

Generating a random enum in java

Tuesday, November 20th, 2007

Here’s a code fragment for how to create a random enum in java from an Enum class object clazz (rnd is an object of type java.util.Random)


Object[] objs = EnumSet.allOf(clazz).toArray();
return objs[rnd.nextInt(objs.length)];

Generating a Random String in Java

Tuesday, November 20th, 2007

I have had a need to create a string in java. I wanted it to be clearly a string, and thus, I decided to make it all lower cases, with spaces. This is the resulting code, inspired by some googling, but since I found nothing for exactly what I wanted, I include it here:

/** In tests, I prefer my random numbers to be identical on identical runs. **/
private static Random rnd = new Random(123456789L);
private static String raw = "abcdefghijklmnoprstu ";
private String randomStr() {
    // if you want the probability of duplication to be small for 10^n iterations of this
    // code, then replace 4 with n.
    char[] chars = new char[4 + rnd.nextInt(50)];
    for (int i = 0; i < chars.length ;i++) {
        chars[i] = raw.charAt(rnd.nextInt(raw.length()));
    }
    return new String(chars);
}