Why is it mandatory to mention the Type information before the return type in case of static as well as non-static methods

时间:2017-06-06 16:29:46

标签: java generics static

I need to understand the need of putting a Type before the return type in case of both, static and non-static classes. Is it only to ensure that the method abides by the type, or is there some other part of the story.

2 个答案:

答案 0 :(得分:0)

语言就是这样设计的。如果你不喜欢它,不要使用Java。请尝试使用C#,其中方法可以像这样声明:

void MyMethod<T>(T someParam) { ... }

JLS chapter 18显示TypeParameters声明如下:

TypeParameters:
    < TypeParameter { , TypeParameter } >

TypeParameter:
    Identifier [extends Bound]

Bound:  
    ReferenceType { & ReferenceType }

GenericMethodOrConstructorDecl定义如下:

GenericMethodOrConstructorDecl:
    TypeParameters GenericMethodOrConstructorRest

GenericMethodOrConstructorRest:
    (Type | void) Identifier MethodDeclaratorRest
    Identifier ConstructorDeclaratorRest

您可以在此处看到TypeParameters 位于 GenericMethodOrConstructorRest之前。

至于为什么它是这样设计的,我认为它唯一的效果是它鼓励你先考虑通用参数,然后再考虑返回类型。

答案 1 :(得分:-1)

我想你提到这种方法:

public <T> void myMethod(T t){
}

public <T> T myMethod(){
}

以这种方式指定T类型会对参数或返回的对象设置约束。

当您声明泛型类时,您通常不会在类中声明类型,因为类已在类中声明:

public class MyGenericClass<T>{

对于非泛型类,在方法中声明类型可能会有所帮助。

有多个用例。

例如,它允许根据其调用者分配给该方法的变量类型返回一个类型 编译器确实可以使用目标类型来推断泛型方法调用的类型。

例如,您可以定义一个将一个对象转换为另一个对象的方法:

public <T>> convert(Object object, Class<T> clazz){
     ... // copy by reflection for example
    return (T) convertedObject;
 }

你可以用这种方式调用它:

MyStringWrapper stringWrapper = convert("myString");
相关问题