简体   繁体   English

Java通用类型语法

[英]Java Generic Type syntax

<D extends com.j256.ormlite.dao.Dao<T,?>,T> D getDao(Class<T> clazz)

I am not able to understand above statement 我无法理解上述陈述

getDao(Class clazz) returns D getDao(Class clazz)返回D.

D having following constraints D具有以下约束

D extends com.j256.ormlite.dao.Dao<T,?>

and extra ,T i am not able to understand. 而且我无法理解。

Could you please explain it ? 你能解释一下吗?

This method has two type parameters, D and T , with D having an additional extends constraint, depending on T . 该方法具有两个类型参数DT ,其中D具有附加的extends约束,取决于T Don't get confused by this <T,?>,T syntax; 不要被这个<T,?>,T语法弄糊涂; the ,T does not belong to the constraint, but is the second parameter, telling Java that T is not the name of a concrete class. ,T 属于约束,但第二个参数,告诉Java中T不是一个具体的类的名称。

If you add a space or swap the parameters, it will be clearer. 如果添加空格或交换参数,它将更清晰。 Here's a similar, but somewhat simpler example. 这是一个类似但有点简单的例子。 These method signatures are all equivalent: 这些方法签名都是等效的:

<D extends List<T>,T>   D createListOf(Class<T> clazz)  // your version
<D extends List<T>, T>  D createListOf(Class<T> clazz)  // extra space
<T, D extends List<T>>  D createListOf(Class<T> clazz)  // different order

Keep in mind that, even though it may seem apparent that T is another type parameter, this is not clear to Java. 请记住,即使看起来很明显T是另一个类型参数,但这对Java来说并不清楚。 There could be an actual class named T , so we have to be explicit that T is a type parameter. 可能有一个名为T的实际类,因此我们必须明确T是一个类型参数。

class T { ... } // this T is not what I want!

Conversely, type parameters are not restricted to single characters. 相反,类型参数不限于单个字符。 You could also have a type parameter called Foo , or even String , if you want to utterly confuse your co-workers. 如果你想彻底混淆你的同事,你也可以有一个名为Foo的类型参数,甚至是String Maybe that makes clear why the declaration of all type parameters using <...> is necessary. 也许这清楚地表明为什么使用<...>声明所有类型参数是必要的。

// just a deterrent example; don't do this! String as parameter, not class
<String, Foo extends List<String>> Foo createListOf(Class<String> clazz)

This method will: 这种方法将:

  • Return an object of type D 返回D类型的对象
  • Where D is or extends com.j256.ormlite.dao.Dao , parametrized with an object of type T or extending/implementing T and an unknown type parameter 其中D是或扩展com.j256.ormlite.dao.Dao ,使用类型为T的对象进行参数化或扩展/实现T和未知类型参数
  • If given as argument a class of type T 如果作为参数给出类型为T的类

It uses a lot of generic abstraction, which is not surprising given it delivers a DAO (Data Access Object). 它使用了很多通用抽象,这并不奇怪,因为它提供了DAO(数据访问对象)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM