Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

java - Generic method without parameters

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

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

1 Reply

0 votes
by (71.8m points)

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`
  } 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...