不带参数的通用方法 [英] Generic method without parameters

查看:96
本文介绍了不带参数的通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对我的代码感到困惑,它包含一个不带参数的泛型方法,那么这种方法的返回泛型类型是什么,例如:

  static< T>例如< T> getObj(){
返回新的示例< T>(){

public T getObject(){
return null;
}

};
}

这是通过以下方式调用的:

 示例< String> exm = getObj(); //它接受任何字符串,比如在这种情况下或者Object和所有的

接口示例的定义为:

  public interface example< T> {

T getObject();
}

我的问题:例子< String> exm 正在接受String,Object和一切。那么在什么时候泛型返回类型被指定为字符串,以及如何??编译器推断出<$ c $的类型 c> T 来自作业 LHS 上使用的具体类型。 此链接


如果类型参数没有出现在方法
参数的类型中,那么编译器无法推断按
检查实际方法参数的类型。如果类型
参数出现在方法的返回类型中,那么编译器将使用
来查看使用返回值的上下文。如果
方法调用显示为赋值的右侧操作数
,则编译器会尝试从赋值左边操作数的
静态类型推断方法的类型参数。 / p>

链接中的示例代码类似于您的问题中的示例代码:

  public final class实用程序{
...
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从LHS推断为'整数'
}
}


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??

解决方案

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

这篇关于不带参数的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆