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.
It is possible to write your own static methods that take explicit parameters and do some calculation or produce some other desired result.
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);
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.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With