简体   繁体   English

这个Java语法是什么意思? (`类 <? extends ContactAccessor> clazz`)

[英]What does this Java syntax mean? (`Class<? extends ContactAccessor> clazz`)

I have been developing android applications for about 1 month now I am getting pretty familiar with the Java syntax but today I stumbled upon this piece of code : 我已经开发了大约1个月的Android应用程序,现在我对Java语法非常熟悉,但今天我偶然发现了这段代码:

try {
    Class<? extends ContactAccessor> clazz =
                      Class.forName(className).asSubclass(ContactAccessor.class);
    sInstance = clazz.newInstance();
} catch (Exception e) {
    throw new IllegalStateException(e);
}

Could somebody explain me what this Class<? extends ContactAccessor> clazz 有人可以解释一下这个Class<? extends ContactAccessor> clazz Class<? extends ContactAccessor> clazz does? Class<? extends ContactAccessor> clazz吗?

Class is used for reflection. Class用于反射。 <> means generic type. <>表示泛型类型。 ? is a generic wildcard. 是一个通用的通配符。 Combined this means that clazz represents definition of a class which is a descendant of ContactAccessor . 结合这意味着clazz表示类的定义,该类是ContactAccessor的后代。 For further explanations, google for generics , wildcards and reflection . 有关进一步说明,谷歌搜索genericswildcardsreflection

That means that you use a class which extend a special base class. 这意味着您使用扩展特殊基类的类。 This is also called Generics in Java. 这在Java中也称为泛型。

This means that the Class you need,it's type is unknown(hence the ? ). 这意味着你需要的Class ,它的类型是未知的(因此? )。 But you know one property of it - that it is a subclass of ContactAccessor . 但是你知道它的一个属性 - 它是ContactAccessor的子类。 And you need to find that particular class - so you do : Class.forName(className).asSubclass(ContactAccessor.class); 你需要找到那个特定的类 - 所以你这样做: Class.forName(className).asSubclass(ContactAccessor.class); saying fetch me the class by it's class,which is a subclass of ContactAccessor . 通过它的类获取类,它是ContactAccessor的子类。

That is an example of Java Generics (more here ). 这是Java Generics的一个例子(更多这里 )。 It implies that the clazz variable will be of a type which extends ContactAccessor . 这意味着clazz变量将是一个扩展ContactAccessor的类型。

It means you have a Class which is ContactAccessor class or a sub class of that class or interface. 这意味着您有一个Class,它是ContactAccessor类或该类或接口的子类。

Since you have ContactAccessor.class already, I would assume you have a sub class. 既然你已经有了ContactAccessor.class ,我会假设你有一个子类。

它定义了一个变量clazz ,它是扩展ContactAccessor类的泛型类的Class对象。

使用通配符(“?”),以便Class只接受ContactAccessor扩展的类,只接受它们中的任何一个。

任何类都是ContactAccessor类的subclass类。

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

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