Tuesday, 24 April 2007

specifying types on static methods with generics

If you're working with generics and writing static methods sometimes you find the need to specify the type in a generic method. e.g.
class Foo {
public static <T> doSomething(String name) {... }
}
Often the compiler often does the right thing
Cheese cheese = Foo.doSomething("Edam");
but sometimes you really need to specify the type. You can use the following syntax to do that
Foo.<Cheese>doSomething("Edam");
Kinda obscure I know but it might come in handy if you're working with generics.

4 comments:

Ricky Clarkson said...

That's fairly noisy syntax, especially as you can't use it with statically imported methods.

The usual cases where you'd expect the compiler to infer the type, and it doesn't, will hopefully be solved in Java 7. Apparently it takes the deletion of 4 lines of code, but pages upon pages of specification rewriting.

Unknown said...

Generic would have been soooo much easier had type inference been handled by the compiler.

James Strachan said...

Agreed! As Ricky says, here's hoping there's more inference in Java 7...

Mohan Radhakrishnan said...

This is not strictly overloading but similar.

public class Loading {

public static <A extends String> A test() {
System.out.println("String");
return null;
}

public static <B extends Integer> B test() {
System.out.println("Number");
return null;
}

public static void main(String[] args) {
Loading.<Integer>test();
Loading.<String>test();
}
}