Meaning of <T, U extends T> in java function declaration

不想你离开。 提交于 2019-12-22 07:20:37

问题


I am seeing this:

public static <T,U extends T> AutoBean<T> getAutoBean(U delegate)

I know the input class is of U type and AutoBean class is of T type and U extends T is the boundary. But what does <T, mean here?

Also, if I am going to write a function to accept the output of getAutoBean, how would you write the function declaration? (i.e. myFunction(getAutoBean(...)), what will the function declaration of myFunction() be?)

Thank you!


回答1:


It just declares the types that your method deals with. That is to say, that it basically has to first declare the generic type names, and only then use them in the signature. <T doesn't mean anything by itself, but the letters within angular brackets mean "Here are the types I am going to use in the method".

As to "myFunction()" to work with the output of getAutoBean(...):

public static  <T> String myFunction(AutoBean<T> arg){ // If you return a generic type object, you will also have to declare it's type parameter in the first angular brackets and in angular brackets after it.
    // do work here
}




回答2:


<T> is the type of the AutoBean that will be returned by the method. Also notice that input parameter type <U> has to extend type <T> for invoking the method.




回答3:


<T,U extends T> is declaring the type parameters for a static method. This method has two type parameters, a type T, and a second type U that extends the first.

These can be different when you explicitly specify bindings for type parameters as in

AutoBean<Object> autoBean = Foo.<Object, String>getAutoBean("delegate");

assuming getAutoBean is a member of class Foo.




回答4:


As lbolit said, declares what your method deals with, i.e. in this case a return type of T and a parameter of U which is a subclass of T.




回答5:


It means the type U must extend the type T. For example, these types could be used in place of T and U.

class TType { }
class UType extends TType { }

As for what <T, means, it's declaring the generic type to be used in the function. Here is example usage:

UType uType = new UType();
AutoBean<TType> autobean = getAutoBean(uType);


来源:https://stackoverflow.com/questions/15491058/meaning-of-t-u-extends-t-in-java-function-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!