What does the dot operator `.` (before the generic parameter) mean?

前端 未结 3 1541
一个人的身影
一个人的身影 2020-12-06 05:30

I saw this code today:

    ImmutableMap, CommandProcessorInterface> immutableMap =
            ImmutableMap.

        
相关标签:
3条回答
  • 2020-12-06 06:14

    Generic methods are methods declared with any generic type parameter. See doc here. The generic type of the method doesn't have to be related to any generic type parameter of the declaring class. The class may or may not be generic.

    When invoking a generic method (static or not) you may specify the generic type but you don't usually see it because it is usually autodetected. That syntax you found is the one to specify it.

    If there is a method declared like this:

    <T> void fromArrayToCollection(T[] a, Collection<T> c) { ...
    

    you may call it like this:

    Integer[] a = ...
    ArrayList<Integer> l = ...
    x.fromArrayToCollection(a, l);
    

    but if you have one like this:

    <T> Collection<T> myMethod(int c) {
      return new ArrayList<T>(c);
    }
    

    Then you have two ways to clarify the type to the compiler. You can give it enough information in two ways.

    One is specifying the type in the call:

    Object c = x.<Integer>myMethod(5);
    

    The other is with a typecast (explicit or implicit by assigning to a variable):

    Collection<Integer> c = x.myMethod(5);
    
    0 讨论(0)
  • 2020-12-06 06:20

    It concerns a static method ImmutableMap.of. This has its own generic type parameters.

    class Test {
    
    static <T> T f() { return null; }
    
    void t() {
        String s = Test.f();                 // Inferred from LHS.
        String t = Test.<String>f();         // Not needed.
        int n = Test.<String>f().length();   // Needed.
    }
    

    In your case it seems not really needed, but there I am on thin ice, as the generic type inference became a bit stronger in Java 8.

    0 讨论(0)
  • 2020-12-06 06:28

    It means you're invoking a generic static method, called of in the ImmutableMap class.

    It's pretty much the same as you're invoking a static method, nested in some class:

    SomeClass.staticMethod();
    

    For the cases when your method has a type-parameter defined, you can explicitly provide the generic type and this is done like this:

    SomeClass.<Type>genericStaticMethod();
    

    And to answer you final question:

    What is the difference between ImmutableMap<Class...> and ImmutableMap.<Class... ?

    The first is usually used when creating an instance of a generic class. It's used to define the generic-type on class level, while the second is used to invoke a generic static method that's nested in some class.

    0 讨论(0)
提交回复
热议问题