Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was confused with my code that includes a generic method that takes no parameters, so what will be the return generic type of such a method, eg:

static <T> example<T> getObj() {
    return new example<T>() {

        public T getObject() {
            return null;
        }

    };
}

and this was called via:

example<String> exm = getObj(); // it accepts anything String like in this case or Object and everything

the interface example's defination is:

public interface example<T> {

    T getObject();
}

My question:example<String> exm is accepting String, Object and everything. So at what time generic return type is specified as String and how??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
319 views
Welcome To Ask or Share your Answers For Others

1 Answer

The compiler infers the type of T from the concrete type used on the LHS of the assignment.

From this link:

If the type parameter does not appear in the types of the method arguments, then the compiler cannot infer the type arguments by examining the types of the actual method arguments. If the type parameter appears in the method's return type, then the compiler takes a look at the context in which the return value is used. If the method call appears as the righthand side operand of an assignment, then the compiler tries to infer the method's type arguments from the static type of the lefthand side operand of the assignment.

The example code in the link is similar to the one in your question:

public final class Utilities { 
  ... 
  public static <T> HashSet<T> create(int size) {  
    return new HashSet<T>(size);  
  } 
} 
public final class Test 
  public static void main(String[] args) { 
    HashSet<Integer> hi = Utilities.create(10); // T is inferred from LHS to be `Integer`
  } 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...