Learning new things…

There are a couple of new things that I’ve learnt since Uni ended.

The first I picked up for from the project I’m doing for the summer. It’s based off of other peoples code so I’ve been looking through that. It’s written in C# which is something I’ve never had any cause to look at or read before, so when looking at the code there were things that I thought of as strange C# syntaxes but were actually nice little hacks. One of these things was ClassName.Instance.method(). At first I thought this was absolute madness and sheer C# witchery, but it is a really clever little hack. What it does is calls Instance which is a static method in the class ClassName (but works just as well with a static variable) which returns an instance of that class. This is great if a program only uses a singe instance of a class. Instead of passing references of the object to all the other objects which need it, the code just needs to call ClassName.Instance to get the instance of it. This means if something gets added later on then you don’t have to worry about maybe having to change the constructor, parameters and fields, you can just add the one line you need to get the instance. See the bottom of this post for an example in Java.

The second thing I’ve learnt is something I’ve always though should be possible through using interfaces in Java and it turns out I was right. This is the joys and wonders of dynamic class loading. I’ve always thought that there must be a way to add new functionality by changing a class that implements the same interface that the program uses without having to recompile anything. Today I decided to look into how to do this properly. A few things brought this investigation on. I’ve been playing about with some Perl and have thoroughly enjoyed being to use normal console commands by wrapping text in “’s, this is pure genius on Perls part. The other thig that brought this on was that the C# code I was given did this, although it used subclasses instead of interfaces (does C# have interfaces?) and some sort of calls to an assembly class. Any way this is done in Java by using Class.forName(“class name”).newInstance().
I think this a great tool and I show an example in the code below.

public class FunWithJava{

public static FunWithJava instance = new FunWithJava();

public static FunWithJava Instance(){
return instance;
}

public int val = 4;

public static void main(String[] args){
try{
//FWJ is an interface. I made three classes that implement it.
//Specifiy the name of the class you want on the command line
FWJ j = (FWJ)(Class.forName(args[0]).newInstance());
Instance().inc();
instance.inc();
instance.out(instance.val, j.getValue());
}
catch(Exception e){}
}

public void inc(){
val++;
}

public void out(int x, int y){
System.out.println(x + ” ” + y);
}

}

Leave a Reply