简体   繁体   English

java.lang.Class和泛型

[英]java.lang.Class and generics

On this gwt javadoc page http://www.gwtproject.org/javadoc/latest/com/google/gwt/core/client/GWT.html java.lang.Class<?> is passed as parameter to the create function. 在此gwt javadoc页面上, http://www.gwtproject.org/javadoc/latest/com/google/gwt/core/client/GWT.html java.lang.Class<?>作为参数传递给create函数。 How is this valid?.. I could understand something like create(List<Class> classLiteral) or create(java.lang.Class classLiteral) but how the way it is used there confuses me greatly. 这如何有效?..我可以理解诸如create(List<Class> classLiteral)create(java.lang.Class classLiteral)但是在那里使用它的方式使我极大地困惑。 Clarifications are much appreciated 澄清非常感谢

java.lang.Class<?> is the full type declaration of the instance. java.lang.Class<?>是实例的完整类型声明。 It is equivalent to 相当于

import java.lang.Class;

...

static <T> T create(Class<?> classLiteral) ...

They are just being thorough in the javadoc. 它们只是在Javadoc中是详尽的。 java.lang.Class is a java class that represents classes. java.lang.Class是代表类的Java类。 You can read its javadoc here . 您可以在此处阅读其javadoc。

You can access the Class object of a class with 您可以使用以下命令访问类的Class对象

YourClass.class // where class is a reserved java keyword will return an instance of type Class<YourClass>

If you have an instance 如果您有实例

YourClass yourInstance = ...
yourInstance.getClass(); // will return an instance of type Class<YourClass>

If <?> is confusing you, it's known as a wildcard. 如果<?>使您感到困惑,则称为通配符。 You can read more about it here . 您可以在此处了解更多信息。

In this situation, the method calls for a class literal, not an instance of a class. 在这种情况下,该方法需要类文字,而不是类的实例。 This means you are passing an actual class to the method instead of an instance of a class. 这意味着您正在将实际的类传递给方法,而不是类的实例。

An example of this is if you were to call: 例如,如果您要致电:

create(MyClass.class); 创建(MyClass.class);

Here, you're passing a Class object, but not an instance of MyClass. 在这里,您传递的是Class对象,而不是MyClass的实例。 So, the create method is asking for a Class object, not an instance of whatever Class you pass into it. 因此,create方法要求的是Class对象,而不是您要传递给它的任何Class的实例。

If it were class(java.lang.Class classLiteral), then it would be calling for an instance of any object that extends class. 如果它是class(java.lang.Class classLiteral),则它将调用扩展class的任何对象的实例。

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

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