Java Reference
In-Depth Information
Therearemanysituationswhereassertionsshouldbeused.Thesesituationsorganize
intointernalinvariant,control-flowinvariant,anddesign-by-contractcategories.Anin-
variant is something that does not change.
Although there are many situations where assertions should be used, there also are
situationswheretheyshouldbeavoided.Forexample,youshouldnotuseassertionsto
check the arguments that are passed to public methods.
The compiler records assertions in the classfile. However, assertions are disabled at
runtimebecausetheycanaffectperformance.Youmustenabletheclassfile'sassertions
before you can test assumptions about the behaviors of your classes.
Annotationsareinstancesofannotationtypesandassociatemetadatawithapplication
elements.Theyareexpressedinsourcecodebyprefixingtheirtypenameswith
@
sym-
bols. For example,
@Readonly
is an annotation and
Readonly
is its type.
Java supplies a wide variety of annotation types, including the compiler-oriented
Override
,
Deprecated
,
SuppressWarnings
, and
SafeVarargs
types.
However,youcanalsodeclareyourownannotationtypesbyusingthe
@interface
syntax.
Annotationtypescanbeannotatedwithmeta-annotationsthatidentifytheapplication
elements they can target (such as constructors, methods, or fields), their retention
policies, and other characteristics.
Annotations whosetypesareassignedaruntime retention policyvia
@Retention
annotations can be processed at runtime using custom applications or Java's
apt
tool,
whose functionality has been integrated into the compiler starting with Java 6.
Java 5 introduced generics, language features for declaring and using type-agnostic
classesandinterfaces.WhenworkingwithJava'sCollectionsFramework,thesefeatures
help you avoid
ClassCastException
s.
Agenerictypeisaclassorinterfacethatintroducesafamilyofparameterizedtypes
bydeclaringaformaltypeparameterlist.Thetypenamethatreplacesatypeparameter
is known as an actual type argument.
Therearefivekindsofactualtypearguments:concretetype,concreteparameterized
type,arraytype,typeparameter,andwildcard.Furthermore,agenerictypealsoidenti-
fies a raw type, which is a generic type without its type parameters.
Many type parameters are unbounded in that they can accept any actual type argu-
ment. To restrict actual type arguments, you can specify an upper bound, a type that
serves as an upper limit on the types that can be chosen as actual type arguments.
The upper bound is specified via reserved word
extends
followed by a type name.
However, lower bounds are not supported.