Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking statically imported method with explicit type parameters

Tags:

java

generics

This is the follow up of my question here: Weird Java generic.

If I have a code like this:

Casts.<X, T> cast(iterable[index]); 

Can I add a static import and do:

<X, T> cast(iterable[index]); 

Eclipse doesn't allow this. But after seeing so many bugs with static import in Eclipse, I'm not that certain.

like image 498
nanda Avatar asked Jan 12 '10 16:01

nanda


People also ask

Can a static method have explicit parameters?

It is possible to write your own static methods that take explicit parameters and do some calculation or produce some other desired result.

How do you use generics with static methods?

For static generic methods, the type parameter section must appear before the method's return type. The complete syntax for invoking this method would be: Pair<Integer, String> p1 = new Pair<>(1, "apple"); Pair<Integer, String> p2 = new Pair<>(2, "pear"); boolean same = Util. <Integer, String>compare(p1, p2);

Do generic methods have to be static?

Static and non-static generic methods are allowed, as well as generic class constructors. The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type.


1 Answers

No, you can't : I just confirmed this via some test code.

PS > javac -version javac 1.6.0_04 

Casts.java

public class Casts {     public static <From, To> To cast(final From object)     {         return (To)object;     } } 

Test.java

import static Casts.cast;  public class Test {     public static void main(String[] args)     {         final Integer integer = new Integer(5);          // This one compiles fine.         final Number number = Casts.<Integer, Number>cast(integer);          // This one fails compilation:         // PS> javac Test.java         // Test.java:11: illegal start of expression         //             final Number number = <Integer, Number>cast(integer);         //                                                    ^         // Test.java:11: not a statement         //             final Number number = <Integer, Number>cast(integer);         //                                                        ^         final String string = <Integer, String>cast(integer);     } } 
like image 90
jdmichal Avatar answered Sep 19 '22 17:09

jdmichal