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 :
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
does?
Class
is used for reflection. <>
means generic type. ?
is a generic wildcard. Combined this means that clazz
represents definition of a class which is a descendant of ContactAccessor
. For further explanations, google for generics
, wildcards
and reflection
.
That means that you use a class which extend a special base class. This is also called Generics in Java.
This means that the Class
you need,it's type is unknown(hence the ?
). But you know one property of it - that it is a subclass of ContactAccessor
. And you need to find that particular class - so you do : Class.forName(className).asSubclass(ContactAccessor.class);
saying fetch me the class by it's class,which is a subclass of ContactAccessor
.
That is an example of Java Generics (more here ). It implies that the clazz
variable will be of a type which extends ContactAccessor
.
It means you have a Class which is ContactAccessor class or a sub class of that class or interface.
Since you have ContactAccessor.class
already, I would assume you have a sub class.
它定义了一个变量clazz
,它是扩展ContactAccessor
类的泛型类的Class
对象。
使用通配符(“?”),以便Class只接受ContactAccessor扩展的类,只接受它们中的任何一个。
任何类都是ContactAccessor
类的subclass
类。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.