Chathura Herath 's Blog

My Photo
Name:
Location: Bloomington, Indiana, United States

Saturday, February 28, 2009

Java method level generics - Getting First Element from an Iterator.

There are ample examples where you are given an iterator but you are only interested in the first element of the collection. Following through some code i had to read, which was doing WSDL parsing, I ran into some code which most probably annoyed the programmer because of the repeating code of the same form that had to be written for different Iterator types, to loop through the iterator and extract the first element. One solution, besides writing helper for each case is to not do typing at all and do non generic helper method.


public static Object getFirst(Iterable itr){
for (Object object : itr) {
return object;
}
throw new RuntimeException("Iterator empty");
}


Obviously this is not why i wrote this blog. I wrote down the following code which is type safe and gives exactly what i want. This makes use of java method level templates. This is type safe because when some one calls this method the templates will be instantiated and the return values are obviously typed based on the instantiation happened at the caller and no type casting necessary.


public static <T extends Object> T getfirst(Iterable<T> vals) {
for (T val: vals) {
return val;
}
throw new RuntimeException("Iterator empty");
}

Tuesday, February 03, 2009

Generic Online web service client

As i ve mentioned many times before Eclipse WTP is cool for many reasons, one of them being the ability to generate a web service client to test a service in an instant.

Lately i came across this online tool to make web service call, and its pretty useful for testing purposes and does save you time. It would get the WSDL (as a http url or otherwise) and would generate a web client which would have the text boxes for the different simple types that would build the complex type.

One client can be found in service-repository and another at soap-client.

Labels: ,