Javac flags and Eclipse settings to process Class.<GenericType>method() invocations
It happens to see
Collections.<Object>asList(...)
method invocations in the code, but Eclipse seems do not understand this(with my configuration) and shows this as compilation error.
Is my Eclipse configuration wrong? Or this doesn't work with Sun compiler (jdk 1.6.013)? What should I check / enable for th开发者_如何学运维ing like this?
If Collections
is meant to be java.util.Collections
, then Eclipse is correct as there is no Collections.asList()
.
I think you meant Arrays.asList()
.
In java typed methods depend on some sort of input to determine the output, so you could declare a method
public List<T> asList(T[] myArray) {
...
}
When calling that method you just pass in your class and the compiler knows what the return type is.
String[] myArray = {"asdf", "asdf"};
List<String> result = asList(myArray);
Alternatively, you could have a typed class that uses that type parameter to determine result
public class Foo<T> {
public void myMethod(T myObject) {
..do something
}
}
If you create a Foo like
Foo<String> foo = new Foo<String>();
you can only invoke myMethod with a String
foo.myMethod("asdf"); //okay
foo.myMethod(new BigInteger(1)); //not okay
There are a lot more things you can do with typed objects, but hopefully this gets to what you were asking about.
精彩评论