Wednesday, February 25, 2009

First Post! Java for the Command Line

I keep coming up with ideas for blog posts, but never end up writing them.
So, I've decided to use write or die to try and get ideas out there, with only a little bit of polish.

The first idea here is the Java shell tool. I probably won't get around to implementing it, but it's pretty neat.

Reflection in Java gives you a lot of runtime flexibility. Java is not usually used as a scripting language, but you should be able to quickly make an interesting amount of Java "command line" accessible with a couple reflection calls. I'll call this command line access tool "javait". We want javait to pass stuff around through pipes, we can do that through serialization. I think a good default is that javait instances pass around a single List object through pipes.

To hook it to regular shell programs, just make a "javaize" that makes a list of lines from standard input, and an "unjavaize" that takes a list and just runs toString on each of the list members and prints them. So what does javait do? Allows you to call a method, then returns the result to standard out. If the method doesn't return a list, just stick it in one.

In short, I'd like the following to work:

grep "Name: " file | javaize | javait "MyClass.substitute" "theStandardInList" "namepattern" "replacenamepattern" | unjavaize

Some problems I can think of with javait are finding a nice syntax for calling methods on the command line (and adding support for non-static methods), you need a special argument to represent standard in, and probably some flexible syntax to add in the extra arguments. I think there are some neat things that you could do with even a hacked together version of this.

Think it's a bit boring (or already done)? Google up some shell "one-liners" and see how many you can make.

Why not just use an actual scripting language? It's interesting in a "look how much I can abuse this" way and I think it's neat to pass around these strict-ish Java objects around through pipes.


No comments:

Post a Comment