I found a method like the one below.
public void simpleTest(Class <? extends ParentClass> myClass){
}
I didn't understand the expression : Class <? extends ParentClass> myClass
Class <? extends ParentClass> myClass
here.
Can anyone explain it?
Class <? extends ParentClass> myClass
Class <? extends ParentClass> myClass
is a method argument whose type is a Class that is parameterized to ensure that what's passed is a Class that represents some type that is a subtype of ParentClass.
ie given:
class ParentParentClass {}
class ParentClass extends ParentParentClass {}
class ChildClass extends ParentClass {}
class ChildChildClass extends ChildClass {}
public void simpleTest(Class <? extends ParentClass> myClass) {}
These are valid:
simpleTest(ParentClass.class);
simpleTest(ChildClass.class);
simpleTest(ChildChildClass.class);
These aren't valid because the argument doesn't "fit" inside the required type:
simpleTest(ParentParentClass.class);
simpleTest(String.class);
simpleTest(Date.class);
simpleTest(Object.class);
From the javadoc of java.lang.Class<T>
:
T - the type of the class modeled by this Class object. For example, the type of String.class is
Class<String>
. UseClass<?>
if the class being modeled is unknown.
Now replace String with your class: it's a Class of a type which is a ParentClass or a subclass of ParentClass.
Class myClass - means that myClass should be aa sub type of ParentClass.
class MyClass extends ParentClass {
}
simpleTest(ParentClass.class); // this is ok
simpleTest(MyClass.class); // this is ok
class SomeOtherClass {
}
simpleTest(SomeOtherClass.class); // will result in compiler error
It's a generic method taking a parametrized class.
It might be helpful to first consider a simpler generics example: List<? extends ParentClass>
List<? extends ParentClass>
means it's a List that only takes objects that fulfill the is-a relationship with ParentClass. Ie the parameter of the List implementation is-a ParentClass, but the type of the whole thing List<? extends ParentClass>
List<? extends ParentClass>
is List.
In your example, just substitute "Class" instead of "List". myClass
is a Class, ie you can call the method with something like "MyClassName.class". Further, the parameter of the Class of my Class is-a ParentClass. This basically means that you can only pass the Class of ParentClass or its subclasses to the method.
See also: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html
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.