Class (Java Platform SE 8 ) - Oracle Help Center

文章推薦指數: 80 %
投票人數:10人

Instances of the class Class represent classes and interfaces in a running Java application. An enum is a kind of class and an annotation is a kind of ... Skipnavigationlinks Overview Package Class Use Tree Deprecated Index Help Java™ PlatformStandard Ed. 8 Prev Class Next Class Frames No Frames All Classes Summary:  Nested |  Field |  Constr |  Method Detail:  Field |  Constr |  Method java.lang.Object java.lang.Class TypeParameters: T-thetypeoftheclassmodeledbythisClass object.Forexample,thetypeofString.classisClass.UseClass>iftheclassbeingmodeledis unknown. AllImplementedInterfaces: Serializable,AnnotatedElement,GenericDeclaration,Type publicfinalclassClass extendsObject implementsSerializable,GenericDeclaration,Type,AnnotatedElement InstancesoftheclassClassrepresentclassesand interfacesinarunningJavaapplication.Anenumisakindof classandanannotationisakindofinterface.Everyarrayalso belongstoaclassthatisreflectedasaClassobject thatissharedbyallarrayswiththesameelementtypeandnumber ofdimensions.TheprimitiveJavatypes(boolean, byte,char,short, int,long,float,and double),andthekeywordvoidarealso representedasClassobjects. Classhasnopublicconstructor.InsteadClass objectsareconstructedautomaticallybytheJavaVirtualMachineasclasses areloadedandbycallstothedefineClassmethodintheclass loader. ThefollowingexampleusesaClassobjecttoprintthe classnameofanobject: voidprintClassName(Objectobj){ System.out.println("Theclassof"+obj+ "is"+obj.getClass().getName()); } ItisalsopossibletogettheClassobjectforanamed type(orforvoid)usingaclassliteral.SeeSection15.8.2of TheJava™LanguageSpecification. Forexample: System.out.println("ThenameofclassFoois:"+Foo.class.getName()); Since: JDK1.0 SeeAlso: ClassLoader.defineClass(byte[],int,int), SerializedForm MethodSummary AllMethods StaticMethods InstanceMethods ConcreteMethods  ModifierandType MethodandDescription  Class asSubclass(Class clazz) CaststhisClassobjecttorepresentasubclassoftheclass representedbythespecifiedclassobject. T cast(Object obj) Castsanobjecttotheclassorinterfacerepresented bythisClassobject. boolean desiredAssertionStatus() Returnstheassertionstatusthatwouldbeassignedtothis classifitweretobeinitializedatthetimethismethodisinvoked. staticClass> forName(String className) ReturnstheClassobjectassociatedwiththeclassor interfacewiththegivenstringname. staticClass> forName(String name, boolean initialize, ClassLoader loader) ReturnstheClassobjectassociatedwiththeclassor interfacewiththegivenstringname,usingthegivenclassloader. AnnotatedType[] getAnnotatedInterfaces() ReturnsanarrayofAnnotatedTypeobjectsthatrepresenttheuse oftypestospecifysuperinterfacesoftheentityrepresentedbythis Classobject. AnnotatedType getAnnotatedSuperclass() ReturnsanAnnotatedTypeobjectthatrepresentstheuseofa typetospecifythesuperclassoftheentityrepresentedbythisClassobject. A getAnnotation(Class annotationClass) Returnsthiselement'sannotationforthespecifiedtypeif suchanannotationispresent,elsenull. Annotation[] getAnnotations() Returnsannotationsthatarepresentonthiselement. A[] getAnnotationsByType(Class annotationClass) Returnsannotationsthatareassociatedwiththiselement. String getCanonicalName() Returnsthecanonicalnameoftheunderlyingclassas definedbytheJavaLanguageSpecification. Class>[] getClasses() ReturnsanarraycontainingClassobjectsrepresentingall thepublicclassesandinterfacesthataremembersoftheclass representedbythisClassobject. ClassLoader getClassLoader() Returnstheclassloaderfortheclass. Class> getComponentType() ReturnstheClassrepresentingthecomponenttypeofan array. Constructor getConstructor(Class>... parameterTypes) ReturnsaConstructorobjectthatreflectsthespecified publicconstructoroftheclassrepresentedbythisClass object. Constructor>[] getConstructors() ReturnsanarraycontainingConstructorobjectsreflecting allthepublicconstructorsoftheclassrepresentedbythis Classobject. A getDeclaredAnnotation(Class annotationClass) Returnsthiselement'sannotationforthespecifiedtypeif suchanannotationisdirectlypresent,elsenull. Annotation[] getDeclaredAnnotations() Returnsannotationsthataredirectlypresentonthiselement. A[] getDeclaredAnnotationsByType(Class annotationClass) Returnsthiselement'sannotation(s)forthespecifiedtypeif suchannotationsareeitherdirectlypresentor indirectlypresent. Class>[] getDeclaredClasses() ReturnsanarrayofClassobjectsreflectingallthe classesandinterfacesdeclaredasmembersoftheclassrepresentedby thisClassobject. Constructor getDeclaredConstructor(Class>... parameterTypes) ReturnsaConstructorobjectthatreflectsthespecified constructoroftheclassorinterfacerepresentedbythis Classobject. Constructor>[] getDeclaredConstructors() ReturnsanarrayofConstructorobjectsreflectingallthe constructorsdeclaredbytheclassrepresentedbythis Classobject. Field getDeclaredField(String name) ReturnsaFieldobjectthatreflectsthespecifieddeclared fieldoftheclassorinterfacerepresentedbythisClass object. Field[] getDeclaredFields() ReturnsanarrayofFieldobjectsreflectingallthefields declaredbytheclassorinterfacerepresentedbythis Classobject. Method getDeclaredMethod(String name, Class>... parameterTypes) ReturnsaMethodobjectthatreflectsthespecified declaredmethodoftheclassorinterfacerepresentedbythis Classobject. Method[] getDeclaredMethods() ReturnsanarraycontainingMethodobjectsreflectingallthe declaredmethodsoftheclassorinterfacerepresentedbythisClassobject,includingpublic,protected,default(package) access,andprivatemethods,butexcludinginheritedmethods. Class> getDeclaringClass() IftheclassorinterfacerepresentedbythisClassobject isamemberofanotherclass,returnstheClassobject representingtheclassinwhichitwasdeclared. Class> getEnclosingClass() Returnstheimmediatelyenclosingclassoftheunderlying class. Constructor> getEnclosingConstructor() IfthisClassobjectrepresentsalocaloranonymous classwithinaconstructor,returnsaConstructorobjectrepresenting theimmediatelyenclosingconstructoroftheunderlying class. Method getEnclosingMethod() IfthisClassobjectrepresentsalocaloranonymous classwithinamethod,returnsaMethodobjectrepresentingthe immediatelyenclosingmethodoftheunderlyingclass. T[] getEnumConstants() Returnstheelementsofthisenumclassornullifthis Classobjectdoesnotrepresentanenumtype. Field getField(String name) ReturnsaFieldobjectthatreflectsthespecifiedpublicmember fieldoftheclassorinterfacerepresentedbythisClass object. Field[] getFields() ReturnsanarraycontainingFieldobjectsreflectingall theaccessiblepublicfieldsoftheclassorinterfacerepresentedby thisClassobject. Type[] getGenericInterfaces() ReturnstheTypesrepresentingtheinterfaces directlyimplementedbytheclassorinterfacerepresentedby thisobject. Type getGenericSuperclass() ReturnstheTyperepresentingthedirectsuperclassof theentity(class,interface,primitivetypeorvoid)representedby thisClass. Class>[] getInterfaces() Determinestheinterfacesimplementedbytheclassorinterface representedbythisobject. Method getMethod(String name, Class>... parameterTypes) ReturnsaMethodobjectthatreflectsthespecifiedpublic membermethodoftheclassorinterfacerepresentedbythis Classobject. Method[] getMethods() ReturnsanarraycontainingMethodobjectsreflectingallthe publicmethodsoftheclassorinterfacerepresentedbythisClassobject,includingthosedeclaredbytheclassorinterfaceand thoseinheritedfromsuperclassesandsuperinterfaces. int getModifiers() ReturnstheJavalanguagemodifiersforthisclassorinterface,encoded inaninteger. String getName() Returnsthenameoftheentity(class,interface,arrayclass, primitivetype,orvoid)representedbythisClassobject, asaString. Package getPackage() Getsthepackageforthisclass. ProtectionDomain getProtectionDomain() ReturnstheProtectionDomainofthisclass. URL getResource(String name) Findsaresourcewithagivenname. InputStream getResourceAsStream(String name) Findsaresourcewithagivenname. Object[] getSigners() Getsthesignersofthisclass. String getSimpleName() Returnsthesimplenameoftheunderlyingclassasgiveninthe sourcecode. Class getSuperclass() ReturnstheClassrepresentingthesuperclassoftheentity (class,interface,primitivetypeorvoid)representedbythis Class. String getTypeName() Returnaninformativestringforthenameofthistype. TypeVariable>[] getTypeParameters() ReturnsanarrayofTypeVariableobjectsthatrepresentthe typevariablesdeclaredbythegenericdeclarationrepresentedbythis GenericDeclarationobject,indeclarationorder. boolean isAnnotation() ReturnstrueifthisClassobjectrepresentsanannotation type. boolean isAnnotationPresent(Class annotationClass) Returnstrueifanannotationforthespecifiedtype ispresentonthiselement,elsefalse. boolean isAnonymousClass() Returnstrueifandonlyiftheunderlyingclass isananonymousclass. boolean isArray() DeterminesifthisClassobjectrepresentsanarrayclass. boolean isAssignableFrom(Class> cls) Determinesiftheclassorinterfacerepresentedbythis Classobjectiseitherthesameas,orisasuperclassor superinterfaceof,theclassorinterfacerepresentedbythespecified Classparameter. boolean isEnum() Returnstrueifandonlyifthisclasswasdeclaredasanenuminthe sourcecode. boolean isInstance(Object obj) DeterminesifthespecifiedObjectisassignment-compatible withtheobjectrepresentedbythisClass. boolean isInterface() DeterminesifthespecifiedClassobjectrepresentsan interfacetype. boolean isLocalClass() Returnstrueifandonlyiftheunderlyingclass isalocalclass. boolean isMemberClass() Returnstrueifandonlyiftheunderlyingclass isamemberclass. boolean isPrimitive() DeterminesifthespecifiedClassobjectrepresentsa primitivetype. boolean isSynthetic() Returnstrueifthisclassisasyntheticclass; returnsfalseotherwise. T newInstance() CreatesanewinstanceoftheclassrepresentedbythisClass object. String toGenericString() ReturnsastringdescribingthisClass,including informationaboutmodifiersandtypeparameters. String toString() Convertstheobjecttoastring. Methodsinheritedfromclass java.lang.Object clone,equals,finalize,getClass,hashCode,notify,notifyAll,wait,wait,wait MethodDetail toString public String toString() Convertstheobjecttoastring.Thestringrepresentationisthe string"class"or"interface",followedbyaspace,andthenbythe fullyqualifiednameoftheclassintheformatreturnedby getName.IfthisClassobjectrepresentsa primitivetype,thismethodreturnsthenameoftheprimitivetype.If thisClassobjectrepresentsvoidthismethodreturns "void". Overrides: toString inclass Object Returns: astringrepresentationofthisclassobject. toGenericString public String toGenericString() ReturnsastringdescribingthisClass,including informationaboutmodifiersandtypeparameters. Thestringisformattedasalistoftypemodifiers,ifany, followedbythekindoftype(emptystringforprimitivetypes andclass,enum,interface,or @interface,asappropriate),followed bythetype'sname,followedbyanangle-bracketed comma-separatedlistofthetype'stypeparameters,ifany. Aspaceisusedtoseparatemodifiersfromoneanotherandto separateanymodifiersfromthekindoftype.Themodifiers occurincanonicalorder.Iftherearenotypeparameters,the typeparameterlistiselided. Notethatsinceinformationabouttheruntimerepresentation ofatypeisbeinggenerated,modifiersnotpresentonthe originatingsourcecodeorillegalontheoriginatingsource codemaybepresent. Returns: astringdescribingthisClass,including informationaboutmodifiersandtypeparameters Since: 1.8 forName publicstatic Class> forName(String className) throwsClassNotFoundException ReturnstheClassobjectassociatedwiththeclassor interfacewiththegivenstringname.Invokingthismethodis equivalentto: Class.forName(className,true,currentLoader) wherecurrentLoaderdenotesthedefiningclassloaderof thecurrentclass. Forexample,thefollowingcodefragmentreturnsthe runtimeClassdescriptorfortheclassnamed java.lang.Thread: Classt=Class.forName("java.lang.Thread") AcalltoforName("X")causestheclassnamed Xtobeinitialized. Parameters: className-thefullyqualifiednameofthedesiredclass. Returns: theClassobjectfortheclasswiththe specifiedname. Throws: LinkageError-ifthelinkagefails ExceptionInInitializerError-iftheinitializationprovoked bythismethodfails ClassNotFoundException-iftheclasscannotbelocated forName publicstatic Class> forName(String name, boolean initialize, ClassLoader loader) throwsClassNotFoundException ReturnstheClassobjectassociatedwiththeclassor interfacewiththegivenstringname,usingthegivenclassloader. Giventhefullyqualifiednameforaclassorinterface(inthesame formatreturnedbygetName)thismethodattemptsto locate,load,andlinktheclassorinterface.Thespecifiedclass loaderisusedtoloadtheclassorinterface.Iftheparameter loaderisnull,theclassisloadedthroughthebootstrap classloader.Theclassisinitializedonlyifthe initializeparameteristrueandifithas notbeeninitializedearlier. Ifnamedenotesaprimitivetypeorvoid,anattempt willbemadetolocateauser-definedclassintheunnamedpackagewhose nameisname.Therefore,thismethodcannotbeusedto obtainanyoftheClassobjectsrepresentingprimitive typesorvoid. Ifnamedenotesanarrayclass,thecomponenttypeof thearrayclassisloadedbutnotinitialized. Forexample,inaninstancemethodtheexpression: Class.forName("Foo") isequivalentto: Class.forName("Foo",true,this.getClass().getClassLoader()) Notethatthismethodthrowserrorsrelatedtoloading,linkingor initializingasspecifiedinSections12.2,12.3and12.4ofThe JavaLanguageSpecification. Notethatthismethoddoesnotcheckwhethertherequestedclass isaccessibletoitscaller. Iftheloaderisnull,andasecurity managerispresent,andthecaller'sclassloaderisnotnull,thenthis methodcallsthesecuritymanager'scheckPermissionmethod withaRuntimePermission("getClassLoader")permissionto ensureit'soktoaccessthebootstrapclassloader. Parameters: name-fullyqualifiednameofthedesiredclass initialize-iftruetheclasswillbeinitialized. SeeSection12.4ofTheJavaLanguageSpecification. loader-classloaderfromwhichtheclassmustbeloaded Returns: classobjectrepresentingthedesiredclass Throws: LinkageError-ifthelinkagefails ExceptionInInitializerError-iftheinitializationprovoked bythismethodfails ClassNotFoundException-iftheclasscannotbelocatedby thespecifiedclassloader Since: 1.2 SeeAlso: forName(String), ClassLoader newInstance public T newInstance() throwsInstantiationException, IllegalAccessException CreatesanewinstanceoftheclassrepresentedbythisClass object.Theclassisinstantiatedasifbyanew expressionwithanemptyargumentlist.Theclassisinitializedifit hasnotalreadybeeninitialized. Notethatthismethodpropagatesanyexceptionthrownbythe nullaryconstructor,includingacheckedexception.Useof thismethodeffectivelybypassesthecompile-timeexception checkingthatwouldotherwisebeperformedbythecompiler. TheConstructor.newInstancemethodavoidsthisproblembywrapping anyexceptionthrownbytheconstructorina(checked)InvocationTargetException. Returns: anewlyallocatedinstanceoftheclassrepresentedbythis object. Throws: IllegalAccessException-iftheclassoritsnullary constructorisnotaccessible. InstantiationException-ifthisClassrepresentsanabstractclass, aninterface,anarrayclass,aprimitivetype,orvoid; oriftheclasshasnonullaryconstructor; oriftheinstantiationfailsforsomeotherreason. ExceptionInInitializerError-iftheinitialization provokedbythismethodfails. SecurityException-Ifasecuritymanager,s,ispresentand thecaller'sclassloaderisnotthesameasoran ancestoroftheclassloaderforthecurrentclassand invocationofs.checkPackageAccess()deniesaccesstothepackage ofthisclass. isInstance public boolean isInstance(Object obj) DeterminesifthespecifiedObjectisassignment-compatible withtheobjectrepresentedbythisClass.Thismethodis thedynamicequivalentoftheJavalanguageinstanceof operator.Themethodreturnstrueifthespecified Objectargumentisnon-nullandcanbecasttothe referencetyperepresentedbythisClassobjectwithout raisingaClassCastException.Itreturnsfalse otherwise. Specifically,ifthisClassobjectrepresentsa declaredclass,thismethodreturnstrueifthespecified Objectargumentisaninstanceoftherepresentedclass(or ofanyofitssubclasses);itreturnsfalseotherwise.If thisClassobjectrepresentsanarrayclass,thismethod returnstrueifthespecifiedObjectargument canbeconvertedtoanobjectofthearrayclassbyanidentity conversionorbyawideningreferenceconversion;itreturns falseotherwise.IfthisClassobject representsaninterface,thismethodreturnstrueifthe classoranysuperclassofthespecifiedObjectargument implementsthisinterface;itreturnsfalseotherwise.If thisClassobjectrepresentsaprimitivetype,thismethod returnsfalse. Parameters: obj-theobjecttocheck Returns: trueifobjisaninstanceofthisclass Since: JDK1.1 isAssignableFrom public boolean isAssignableFrom(Class> cls) Determinesiftheclassorinterfacerepresentedbythis Classobjectiseitherthesameas,orisasuperclassor superinterfaceof,theclassorinterfacerepresentedbythespecified Classparameter.Itreturnstrueifso; otherwiseitreturnsfalse.IfthisClass objectrepresentsaprimitivetype,thismethodreturns trueifthespecifiedClassparameteris exactlythisClassobject;otherwiseitreturns false. Specifically,thismethodtestswhetherthetyperepresentedbythe specifiedClassparametercanbeconvertedtothetype representedbythisClassobjectviaanidentityconversion orviaawideningreferenceconversion.SeeTheJavaLanguage Specification,sections5.1.1and5.1.4,fordetails. Parameters: cls-theClassobjecttobechecked Returns: thebooleanvalueindicatingwhetherobjectsofthe typeclscanbeassignedtoobjectsofthisclass Throws: NullPointerException-ifthespecifiedClassparameteris null. Since: JDK1.1 isInterface public boolean isInterface() DeterminesifthespecifiedClassobjectrepresentsan interfacetype. Returns: trueifthisobjectrepresentsaninterface; falseotherwise. isArray public boolean isArray() DeterminesifthisClassobjectrepresentsanarrayclass. Returns: trueifthisobjectrepresentsanarrayclass; falseotherwise. Since: JDK1.1 isPrimitive public boolean isPrimitive() DeterminesifthespecifiedClassobjectrepresentsa primitivetype. ThereareninepredefinedClassobjectstorepresent theeightprimitivetypesandvoid.ThesearecreatedbytheJava VirtualMachine,andhavethesamenamesastheprimitivetypesthat theyrepresent,namelyboolean,byte, char,short,int, long,float,anddouble. Theseobjectsmayonlybeaccessedviathefollowingpublicstatic finalvariables,andaretheonlyClassobjectsforwhich thismethodreturnstrue. Returns: trueifandonlyifthisclassrepresentsaprimitivetype Since: JDK1.1 SeeAlso: Boolean.TYPE, Character.TYPE, Byte.TYPE, Short.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE, Void.TYPE isAnnotation public boolean isAnnotation() ReturnstrueifthisClassobjectrepresentsanannotation type.Notethatifthismethodreturnstrue,isInterface() wouldalsoreturntrue,asallannotationtypesarealsointerfaces. Returns: trueifthisclassobjectrepresentsanannotation type;falseotherwise Since: 1.5 isSynthetic public boolean isSynthetic() Returnstrueifthisclassisasyntheticclass; returnsfalseotherwise. Returns: trueifandonlyifthisclassisasyntheticclassas definedbytheJavaLanguageSpecification. Since: 1.5 SeeTheJava™LanguageSpecification: 13.1TheFormofaBinary getName public String getName() Returnsthenameoftheentity(class,interface,arrayclass, primitivetype,orvoid)representedbythisClassobject, asaString. Ifthisclassobjectrepresentsareferencetypethatisnotan arraytypethenthebinarynameoftheclassisreturned,asspecified by TheJava™LanguageSpecification. Ifthisclassobjectrepresentsaprimitivetypeorvoid,thenthe namereturnedisaStringequaltotheJavalanguage keywordcorrespondingtotheprimitivetypeorvoid. Ifthisclassobjectrepresentsaclassofarrays,thentheinternal formofthenameconsistsofthenameoftheelementtypeprecededby oneormore'['charactersrepresentingthedepthofthearray nesting.Theencodingofelementtypenamesisasfollows: ElementType   Encoding boolean   Z byte   B char   C classorinterface    Lclassname; double   D float   F int   I long   J short   S Theclassorinterfacenameclassnameisthebinarynameof theclassspecifiedabove. Examples: String.class.getName() returns"java.lang.String" byte.class.getName() returns"byte" (newObject[3]).getClass().getName() returns"[Ljava.lang.Object;" (newint[3][4][5][6][7][8][9]).getClass().getName() returns"[[[[[[[I" Returns: thenameoftheclassorinterface representedbythisobject. getClassLoader public ClassLoader getClassLoader() Returnstheclassloaderfortheclass.Someimplementationsmayuse nulltorepresentthebootstrapclassloader.Thismethodwillreturn nullinsuchimplementationsifthisclasswasloadedbythebootstrap classloader. Ifasecuritymanagerispresent,andthecaller'sclassloaderis notnullandthecaller'sclassloaderisnotthesameasoranancestorof theclassloaderfortheclasswhoseclassloaderisrequested,then thismethodcallsthesecuritymanager'scheckPermission methodwithaRuntimePermission("getClassLoader") permissiontoensureit'soktoaccesstheclassloaderfortheclass. Ifthisobject representsaprimitivetypeorvoid,nullisreturned. Returns: theclassloaderthatloadedtheclassorinterface representedbythisobject. Throws: SecurityException-ifasecuritymanagerexistsandits checkPermissionmethoddenies accesstotheclassloaderfortheclass. SeeAlso: ClassLoader, SecurityManager.checkPermission(java.security.Permission), RuntimePermission getTypeParameters public TypeVariable>[] getTypeParameters() ReturnsanarrayofTypeVariableobjectsthatrepresentthe typevariablesdeclaredbythegenericdeclarationrepresentedbythis GenericDeclarationobject,indeclarationorder.Returnsan arrayoflength0iftheunderlyinggenericdeclarationdeclaresnotype variables. Specifiedby: getTypeParameters ininterface GenericDeclaration Returns: anarrayofTypeVariableobjectsthatrepresent thetypevariablesdeclaredbythisgenericdeclaration Throws: GenericSignatureFormatError-ifthegeneric signatureofthisgenericdeclarationdoesnotconformto theformatspecifiedin TheJava™VirtualMachineSpecification Since: 1.5 getSuperclass public Class getSuperclass() ReturnstheClassrepresentingthesuperclassoftheentity (class,interface,primitivetypeorvoid)representedbythis Class.IfthisClassrepresentseitherthe Objectclass,aninterface,aprimitivetype,orvoid,then nullisreturned.Ifthisobjectrepresentsanarrayclassthenthe ClassobjectrepresentingtheObjectclassis returned. Returns: thesuperclassoftheclassrepresentedbythisobject. getGenericSuperclass public Type getGenericSuperclass() ReturnstheTyperepresentingthedirectsuperclassof theentity(class,interface,primitivetypeorvoid)representedby thisClass. Ifthesuperclassisaparameterizedtype,theType objectreturnedmustaccuratelyreflecttheactualtype parametersusedinthesourcecode.Theparameterizedtype representingthesuperclassiscreatedifithadnotbeen createdbefore.SeethedeclarationofParameterizedTypeforthe semanticsofthecreationprocessforparameterizedtypes.If thisClassrepresentseithertheObject class,aninterface,aprimitivetype,orvoid,thennullis returned.Ifthisobjectrepresentsanarrayclassthenthe ClassobjectrepresentingtheObjectclassis returned. Returns: thesuperclassoftheclassrepresentedbythisobject Throws: GenericSignatureFormatError-ifthegeneric classsignaturedoesnotconformtotheformatspecifiedin TheJava™VirtualMachineSpecification TypeNotPresentException-ifthegenericsuperclass referstoanon-existenttypedeclaration MalformedParameterizedTypeException-ifthe genericsuperclassreferstoaparameterizedtypethatcannotbe instantiatedforanyreason Since: 1.5 getPackage public Package getPackage() Getsthepackageforthisclass.Theclassloaderofthisclassisused tofindthepackage.Iftheclasswasloadedbythebootstrapclass loaderthesetofpackagesloadedfromCLASSPATHissearchedtofindthe packageoftheclass.Nullisreturnedifnopackageobjectwascreated bytheclassloaderofthisclass. Packageshaveattributesforversionsandspecificationsonlyifthe informationwasdefinedinthemanifeststhataccompanytheclasses,and iftheclassloadercreatedthepackageinstancewiththeattributes fromthemanifest. Returns: thepackageoftheclass,ornullifnopackage informationisavailablefromthearchiveorcodebase. getInterfaces public Class>[] getInterfaces() Determinestheinterfacesimplementedbytheclassorinterface representedbythisobject. Ifthisobjectrepresentsaclass,thereturnvalueisanarray containingobjectsrepresentingallinterfacesimplementedbythe class.Theorderoftheinterfaceobjectsinthearraycorrespondsto theorderoftheinterfacenamesintheimplementsclause ofthedeclarationoftheclassrepresentedbythisobject.For example,giventhedeclaration: classShimmerimplementsFloorWax,DessertTopping{...} supposethevalueofsisaninstanceof Shimmer;thevalueoftheexpression: s.getClass().getInterfaces()[0] istheClassobjectthatrepresentsinterface FloorWax;andthevalueof: s.getClass().getInterfaces()[1] istheClassobjectthatrepresentsinterface DessertTopping. Ifthisobjectrepresentsaninterface,thearraycontainsobjects representingallinterfacesextendedbytheinterface.Theorderofthe interfaceobjectsinthearraycorrespondstotheorderoftheinterface namesintheextendsclauseofthedeclarationofthe interfacerepresentedbythisobject. Ifthisobjectrepresentsaclassorinterfacethatimplementsno interfaces,themethodreturnsanarrayoflength0. Ifthisobjectrepresentsaprimitivetypeorvoid,themethod returnsanarrayoflength0. IfthisClassobjectrepresentsanarraytype,the interfacesCloneableandjava.io.Serializableare returnedinthatorder. Returns: anarrayofinterfacesimplementedbythisclass. getGenericInterfaces public Type[] getGenericInterfaces() ReturnstheTypesrepresentingtheinterfaces directlyimplementedbytheclassorinterfacerepresentedby thisobject. Ifasuperinterfaceisaparameterizedtype,the Typeobjectreturnedforitmustaccuratelyreflect theactualtypeparametersusedinthesourcecode.The parameterizedtyperepresentingeachsuperinterfaceiscreated ifithadnotbeencreatedbefore.Seethedeclarationof ParameterizedType forthesemanticsofthecreationprocessforparameterized types. Ifthisobjectrepresentsaclass,thereturnvalueisan arraycontainingobjectsrepresentingallinterfaces implementedbytheclass.Theorderoftheinterfaceobjectsin thearraycorrespondstotheorderoftheinterfacenamesin theimplementsclauseofthedeclarationoftheclass representedbythisobject.Inthecaseofanarrayclass,the interfacesCloneableandSerializableare returnedinthatorder. Ifthisobjectrepresentsaninterface,thearraycontains objectsrepresentingallinterfacesdirectlyextendedbythe interface.Theorderoftheinterfaceobjectsinthearray correspondstotheorderoftheinterfacenamesinthe extendsclauseofthedeclarationoftheinterface representedbythisobject. Ifthisobjectrepresentsaclassorinterfacethat implementsnointerfaces,themethodreturnsanarrayoflength 0. Ifthisobjectrepresentsaprimitivetypeorvoid,the methodreturnsanarrayoflength0. Returns: anarrayofinterfacesimplementedbythisclass Throws: GenericSignatureFormatError-ifthegenericclasssignaturedoesnotconformtotheformat specifiedin TheJava™VirtualMachineSpecification TypeNotPresentException-ifanyofthegeneric superinterfacesreferstoanon-existenttypedeclaration MalformedParameterizedTypeException-ifanyofthegenericsuperinterfacesrefertoaparameterized typethatcannotbeinstantiatedforanyreason Since: 1.5 getComponentType public Class> getComponentType() ReturnstheClassrepresentingthecomponenttypeofan array.Ifthisclassdoesnotrepresentanarrayclassthismethod returnsnull. Returns: theClassrepresentingthecomponenttypeofthis classifthisclassisanarray Since: JDK1.1 SeeAlso: Array getModifiers public int getModifiers() ReturnstheJavalanguagemodifiersforthisclassorinterface,encoded inaninteger.ThemodifiersconsistoftheJavaVirtualMachine's constantsforpublic,protected, private,final,static, abstractandinterface;theyshouldbedecoded usingthemethodsofclassModifier. Iftheunderlyingclassisanarrayclass,thenits public,privateandprotected modifiersarethesameasthoseofitscomponenttype.Ifthis Classrepresentsaprimitivetypeorvoid,its publicmodifierisalwaystrue,andits protectedandprivatemodifiersarealways false.Ifthisobjectrepresentsanarrayclass,a primitivetypeorvoid,thenitsfinalmodifierisalways trueanditsinterfacemodifierisalways false.Thevaluesofitsothermodifiersarenotdetermined bythisspecification. ThemodifierencodingsaredefinedinTheJavaVirtualMachine Specification,table4.1. Returns: theintrepresentingthemodifiersforthisclass Since: JDK1.1 SeeAlso: Modifier getSigners public Object[] getSigners() Getsthesignersofthisclass. Returns: thesignersofthisclass,ornulliftherearenosigners.In particular,thismethodreturnsnullifthisobjectrepresents aprimitivetypeorvoid. Since: JDK1.1 getEnclosingMethod public Method getEnclosingMethod() throwsSecurityException IfthisClassobjectrepresentsalocaloranonymous classwithinamethod,returnsaMethodobjectrepresentingthe immediatelyenclosingmethodoftheunderlyingclass.Returns nullotherwise. Inparticular,thismethodreturnsnulliftheunderlying classisalocaloranonymousclassimmediatelyenclosedbyatype declaration,instanceinitializerorstaticinitializer. Returns: theimmediatelyenclosingmethodoftheunderlyingclass,if thatclassisalocaloranonymousclass;otherwisenull. Throws: SecurityException-Ifasecuritymanager,s,ispresentandanyofthe followingconditionsismet: thecaller'sclassloaderisnotthesameasthe classloaderoftheenclosingclassandinvocationof s.checkPermissionmethodwith RuntimePermission("accessDeclaredMembers") deniesaccesstothemethodswithintheenclosingclass thecaller'sclassloaderisnotthesameasoran ancestoroftheclassloaderfortheenclosingclassand invocationofs.checkPackageAccess()deniesaccesstothepackage oftheenclosingclass Since: 1.5 getEnclosingConstructor public Constructor> getEnclosingConstructor() throwsSecurityException IfthisClassobjectrepresentsalocaloranonymous classwithinaconstructor,returnsaConstructorobjectrepresenting theimmediatelyenclosingconstructoroftheunderlying class.Returnsnullotherwise.Inparticular,this methodreturnsnulliftheunderlyingclassisalocal oranonymousclassimmediatelyenclosedbyatypedeclaration, instanceinitializerorstaticinitializer. Returns: theimmediatelyenclosingconstructoroftheunderlyingclass,if thatclassisalocaloranonymousclass;otherwisenull. Throws: SecurityException-Ifasecuritymanager,s,ispresentandanyofthe followingconditionsismet: thecaller'sclassloaderisnotthesameasthe classloaderoftheenclosingclassandinvocationof s.checkPermissionmethodwith RuntimePermission("accessDeclaredMembers") deniesaccesstotheconstructorswithintheenclosingclass thecaller'sclassloaderisnotthesameasoran ancestoroftheclassloaderfortheenclosingclassand invocationofs.checkPackageAccess()deniesaccesstothepackage oftheenclosingclass Since: 1.5 getDeclaringClass public Class> getDeclaringClass() throwsSecurityException IftheclassorinterfacerepresentedbythisClassobject isamemberofanotherclass,returnstheClassobject representingtheclassinwhichitwasdeclared.Thismethodreturns nullifthisclassorinterfaceisnotamemberofanyotherclass.If thisClassobjectrepresentsanarrayclass,aprimitive type,orvoid,thenthismethodreturnsnull. Returns: thedeclaringclassforthisclass Throws: SecurityException-Ifasecuritymanager,s,ispresentandthecaller's classloaderisnotthesameasoranancestoroftheclass loaderforthedeclaringclassandinvocationofs.checkPackageAccess() deniesaccesstothepackageofthedeclaringclass Since: JDK1.1 getEnclosingClass public Class> getEnclosingClass() throwsSecurityException Returnstheimmediatelyenclosingclassoftheunderlying class.Iftheunderlyingclassisatoplevelclassthis methodreturnsnull. Returns: theimmediatelyenclosingclassoftheunderlyingclass Throws: SecurityException-Ifasecuritymanager,s,ispresentandthecaller's classloaderisnotthesameasoranancestoroftheclass loaderfortheenclosingclassandinvocationofs.checkPackageAccess() deniesaccesstothepackageoftheenclosingclass Since: 1.5 getSimpleName public String getSimpleName() Returnsthesimplenameoftheunderlyingclassasgiveninthe sourcecode.Returnsanemptystringiftheunderlyingclassis anonymous. Thesimplenameofanarrayisthesimplenameofthe componenttypewith"[]"appended.Inparticularthesimple nameofanarraywhosecomponenttypeisanonymousis"[]". Returns: thesimplenameoftheunderlyingclass Since: 1.5 getTypeName public String getTypeName() Returnaninformativestringforthenameofthistype. Specifiedby: getTypeName ininterface Type Returns: aninformativestringforthenameofthistype Since: 1.8 getCanonicalName public String getCanonicalName() Returnsthecanonicalnameoftheunderlyingclassas definedbytheJavaLanguageSpecification.Returnsnullif theunderlyingclassdoesnothaveacanonicalname(i.e.,if itisalocaloranonymousclassoranarraywhosecomponent typedoesnothaveacanonicalname). Returns: thecanonicalnameoftheunderlyingclassifitexists,and nullotherwise. Since: 1.5 isAnonymousClass public boolean isAnonymousClass() Returnstrueifandonlyiftheunderlyingclass isananonymousclass. Returns: trueifandonlyifthisclassisananonymousclass. Since: 1.5 isLocalClass public boolean isLocalClass() Returnstrueifandonlyiftheunderlyingclass isalocalclass. Returns: trueifandonlyifthisclassisalocalclass. Since: 1.5 isMemberClass public boolean isMemberClass() Returnstrueifandonlyiftheunderlyingclass isamemberclass. Returns: trueifandonlyifthisclassisamemberclass. Since: 1.5 getClasses public Class>[] getClasses() ReturnsanarraycontainingClassobjectsrepresentingall thepublicclassesandinterfacesthataremembersoftheclass representedbythisClassobject.Thisincludespublic classandinterfacemembersinheritedfromsuperclassesandpublicclass andinterfacemembersdeclaredbytheclass.Thismethodreturnsan arrayoflength0ifthisClassobjecthasnopublicmember classesorinterfaces.Thismethodalsoreturnsanarrayoflength0if thisClassobjectrepresentsaprimitivetype,anarray class,orvoid. Returns: thearrayofClassobjectsrepresentingthepublic membersofthisclass Throws: SecurityException-Ifasecuritymanager,s,ispresentand thecaller'sclassloaderisnotthesameasoran ancestoroftheclassloaderforthecurrentclassand invocationofs.checkPackageAccess()deniesaccesstothepackage ofthisclass. Since: JDK1.1 getFields public Field[] getFields() throwsSecurityException ReturnsanarraycontainingFieldobjectsreflectingall theaccessiblepublicfieldsoftheclassorinterfacerepresentedby thisClassobject. IfthisClassobjectrepresentsaclassorinterfacewithno noaccessiblepublicfields,thenthismethodreturnsanarrayoflength 0. IfthisClassobjectrepresentsaclass,thenthismethod returnsthepublicfieldsoftheclassandofallitssuperclasses. IfthisClassobjectrepresentsaninterface,thenthis methodreturnsthefieldsoftheinterfaceandofallits superinterfaces. IfthisClassobjectrepresentsanarraytype,aprimitive type,orvoid,thenthismethodreturnsanarrayoflength0. Theelementsinthereturnedarrayarenotsortedandarenotinany particularorder. Returns: thearrayofFieldobjectsrepresentingthe publicfields Throws: SecurityException-Ifasecuritymanager,s,ispresentand thecaller'sclassloaderisnotthesameasoran ancestoroftheclassloaderforthecurrentclassand invocationofs.checkPackageAccess()deniesaccesstothepackage ofthisclass. Since: JDK1.1 SeeTheJava™LanguageSpecification: 8.2ClassMembers,8.3FieldDeclarations getMethods public Method[] getMethods() throwsSecurityException ReturnsanarraycontainingMethodobjectsreflectingallthe publicmethodsoftheclassorinterfacerepresentedbythisClassobject,includingthosedeclaredbytheclassorinterfaceand thoseinheritedfromsuperclassesandsuperinterfaces. IfthisClassobjectrepresentsatypethathasmultiple publicmethodswiththesamenameandparametertypes,butdifferent returntypes,thenthereturnedarrayhasaMethodobjectfor eachsuchmethod. IfthisClassobjectrepresentsatypewithaclass initializationmethod,thenthereturnedarraydoes nothaveacorrespondingMethodobject. IfthisClassobjectrepresentsanarraytype,thenthe returnedarrayhasaMethodobjectforeachofthepublic methodsinheritedbythearraytypefromObject.Itdoesnot containaMethodobjectforclone(). IfthisClassobjectrepresentsaninterfacethenthe returnedarraydoesnotcontainanyimplicitlydeclaredmethodsfrom Object.Therefore,ifnomethodsareexplicitlydeclaredin thisinterfaceoranyofitssuperinterfacesthenthereturnedarray haslength0.(NotethataClassobjectwhichrepresentsaclass alwayshaspublicmethods,inheritedfromObject.) IfthisClassobjectrepresentsaprimitivetypeorvoid, thenthereturnedarrayhaslength0. Staticmethodsdeclaredinsuperinterfacesoftheclassorinterface representedbythisClassobjectarenotconsideredmembersof theclassorinterface. Theelementsinthereturnedarrayarenotsortedandarenotinany particularorder. Returns: thearrayofMethodobjectsrepresentingthe publicmethodsofthisclass Throws: SecurityException-Ifasecuritymanager,s,ispresentand thecaller'sclassloaderisnotthesameasoran ancestoroftheclassloaderforthecurrentclassand invocationofs.checkPackageAccess()deniesaccesstothepackage ofthisclass. Since: JDK1.1 SeeTheJava™LanguageSpecification: 8.2ClassMembers,8.4MethodDeclarations getConstructors public Constructor>[] getConstructors() throwsSecurityException ReturnsanarraycontainingConstructorobjectsreflecting allthepublicconstructorsoftheclassrepresentedbythis Classobject.Anarrayoflength0isreturnedifthe classhasnopublicconstructors,oriftheclassisanarrayclass,or iftheclassreflectsaprimitivetypeorvoid. NotethatwhilethismethodreturnsanarrayofConstructorobjects(thatisanarrayofconstructorsfrom thisclass),thereturntypeofthismethodisConstructor>[]andnotConstructor[]as mightbeexpected.Thislessinformativereturntypeis necessarysinceafterbeingreturnedfromthismethod,the arraycouldbemodifiedtoholdConstructorobjectsfor differentclasses,whichwouldviolatethetypeguaranteesof Constructor[]. Returns: thearrayofConstructorobjectsrepresentingthe publicconstructorsofthisclass Throws: SecurityException-Ifasecuritymanager,s,ispresentand thecaller'sclassloaderisnotthesameasoran ancestoroftheclassloaderforthecurrentclassand invocationofs.checkPackageAccess()deniesaccesstothepackage ofthisclass. Since: JDK1.1 getField public Field getField(String name) throwsNoSuchFieldException, SecurityException ReturnsaFieldobjectthatreflectsthespecifiedpublicmember fieldoftheclassorinterfacerepresentedbythisClass object.ThenameparameterisaStringspecifyingthe simplenameofthedesiredfield. Thefieldtobereflectedisdeterminedbythealgorithmthat follows.LetCbetheclassorinterfacerepresentedbythisobject: IfCdeclaresapublicfieldwiththenamespecified,thatisthe fieldtobereflected. Ifnofieldwasfoundinstep1above,thisalgorithmisapplied recursivelytoeachdirectsuperinterfaceofC.Thedirect superinterfacesaresearchedintheordertheyweredeclared. Ifnofieldwasfoundinsteps1and2above,andChasa superclassS,thenthisalgorithmisinvokedrecursivelyuponS. IfChasnosuperclass,thenaNoSuchFieldException isthrown. IfthisClassobjectrepresentsanarraytype,thenthis methoddoesnotfindthelengthfieldofthearraytype. Parameters: name-thefieldname Returns: theFieldobjectofthisclassspecifiedby name Throws: NoSuchFieldException-ifafieldwiththespecifiednameis notfound. NullPointerException-ifnameisnull SecurityException-Ifasecuritymanager,s,ispresentand thecaller'sclassloaderisnotthesameasoran ancestoroftheclassloaderforthecurrentclassand invocationofs.checkPackageAccess()deniesaccesstothepackage ofthisclass. Since: JDK1.1 SeeTheJava™LanguageSpecification: 8.2ClassMembers,8.3FieldDeclarations getMethod public Method getMethod(String name, Class>... parameterTypes) throwsNoSuchMethodException, SecurityException ReturnsaMethodobjectthatreflectsthespecifiedpublic membermethodoftheclassorinterfacerepresentedbythis Classobject.Thenameparameterisa Stringspecifyingthesimplenameofthedesiredmethod.The parameterTypesparameterisanarrayofClass objectsthatidentifythemethod'sformalparametertypes,indeclared order.IfparameterTypesisnull,itis treatedasifitwereanemptyarray. Ifthenameis""or""a NoSuchMethodExceptionisraised.Otherwise,themethodto bereflectedisdeterminedbythealgorithmthatfollows.LetCbethe classorinterfacerepresentedbythisobject: Cissearchedforamatchingmethod,asdefinedbelow.Ifa matchingmethodisfound,itisreflected. Ifnomatchingmethodisfoundbystep1then: IfCisaclassotherthanObject,thenthisalgorithmis invokedrecursivelyonthesuperclassofC. IfCistheclassObject,orifCisaninterface,then thesuperinterfacesofC(ifany)aresearchedforamatching method.Ifanysuchmethodisfound,itisreflected. TofindamatchingmethodinaclassorinterfaceC: IfC declaresexactlyonepublicmethodwiththespecifiednameandexactly thesameformalparametertypes,thatisthemethodreflected.Ifmore thanonesuchmethodisfoundinC,andoneofthesemethodshasa returntypethatismorespecificthananyoftheothers,thatmethodis reflected;otherwiseoneofthemethodsischosenarbitrarily. Notethattheremaybemorethanonematchingmethodina classbecausewhiletheJavalanguageforbidsaclassto declaremultiplemethodswiththesamesignaturebutdifferent returntypes,theJavavirtualmachinedoesnot.This increasedflexibilityinthevirtualmachinecanbeusedto implementvariouslanguagefeatures.Forexample,covariant returnscanbeimplementedwithbridgemethods;thebridge methodandthemethodbeingoverriddenwouldhavethesame signaturebutdifferentreturntypes. IfthisClassobjectrepresentsanarraytype,thenthis methoddoesnotfindtheclone()method. Staticmethodsdeclaredinsuperinterfacesoftheclassorinterface representedbythisClassobjectarenotconsideredmembersof theclassorinterface. Parameters: name-thenameofthemethod parameterTypes-thelistofparameters Returns: theMethodobjectthatmatchesthespecified nameandparameterTypes Throws: NoSuchMethodException-ifamatchingmethodisnotfound orifthenameis""or"". NullPointerException-ifnameisnull SecurityException-Ifasecuritymanager,s,ispresentand thecaller'sclassloaderisnotthesameasoran ancestoroftheclassloaderforthecurrentclassand invocationofs.checkPackageAccess()deniesaccesstothepackage ofthisclass. Since: JDK1.1 SeeTheJava™LanguageSpecification: 8.2ClassMembers,8.4MethodDeclarations getConstructor public Constructor getConstructor(Class>... parameterTypes) throwsNoSuchMethodException, SecurityException ReturnsaConstructorobjectthatreflectsthespecified publicconstructoroftheclassrepresentedbythisClass object.TheparameterTypesparameterisanarrayof Classobjectsthatidentifytheconstructor'sformal parametertypes,indeclaredorder. IfthisClassobjectrepresentsaninnerclass declaredinanon-staticcontext,theformalparametertypes includetheexplicitenclosinginstanceasthefirstparameter. Theconstructortoreflectisthepublicconstructoroftheclass representedbythisClassobjectwhoseformalparameter typesmatchthosespecifiedbyparameterTypes. Parameters: parameterTypes-theparameterarray Returns: theConstructorobjectofthepublicconstructorthat matchesthespecifiedparameterTypes Throws: NoSuchMethodException-ifamatchingmethodisnotfound. SecurityException-Ifasecuritymanager,s,ispresentand thecaller'sclassloaderisnotthesameasoran ancestoroftheclassloaderforthecurrentclassand invocationofs.checkPackageAccess()deniesaccesstothepackage ofthisclass. Since: JDK1.1 getDeclaredClasses public Class>[] getDeclaredClasses() throwsSecurityException ReturnsanarrayofClassobjectsreflectingallthe classesandinterfacesdeclaredasmembersoftheclassrepresentedby thisClassobject.Thisincludespublic,protected,default (package)access,andprivateclassesandinterfacesdeclaredbythe class,butexcludesinheritedclassesandinterfaces.Thismethod returnsanarrayoflength0iftheclassdeclaresnoclassesor interfacesasmembers,orifthisClassobjectrepresentsa primitivetype,anarrayclass,orvoid. Returns: thearrayofClassobjectsrepresentingallthe declaredmembersofthisclass Throws: SecurityException-Ifasecuritymanager,s,ispresentandanyofthe followingconditionsismet: thecaller'sclassloaderisnotthesameasthe classloaderofthisclassandinvocationof s.checkPermissionmethodwith RuntimePermission("accessDeclaredMembers") deniesaccesstothedeclaredclasseswithinthisclass thecaller'sclassloaderisnotthesameasoran ancestoroftheclassloaderforthecurrentclassand invocationofs.checkPackageAccess()deniesaccesstothepackage ofthisclass Since: JDK1.1 getDeclaredFields public Field[] getDeclaredFields() throwsSecurityException ReturnsanarrayofFieldobjectsreflectingallthefields declaredbytheclassorinterfacerepresentedbythis Classobject.Thisincludespublic,protected,default (package)access,andprivatefields,butexcludesinheritedfields. IfthisClassobjectrepresentsaclassorinterfacewithno declaredfields,thenthismethodreturnsanarrayoflength0. IfthisClassobjectrepresentsanarraytype,aprimitive type,orvoid,thenthismethodreturnsanarrayoflength0. Theelementsinthereturnedarrayarenotsortedandarenotinany particularorder. Returns: thearrayofFieldobjectsrepresentingallthe declaredfieldsofthisclass Throws: SecurityException-Ifasecuritymanager,s,ispresentandanyofthe followingconditionsismet: thecaller'sclassloaderisnotthesameasthe classloaderofthisclassandinvocationof s.checkPermissionmethodwith RuntimePermission("accessDeclaredMembers") deniesaccesstothedeclaredfieldswithinthisclass thecaller'sclassloaderisnotthesameasoran ancestoroftheclassloaderforthecurrentclassand invocationofs.checkPackageAccess()deniesaccesstothepackage ofthisclass Since: JDK1.1 SeeTheJava™LanguageSpecification: 8.2ClassMembers,8.3FieldDeclarations getDeclaredMethods public Method[] getDeclaredMethods() throwsSecurityException ReturnsanarraycontainingMethodobjectsreflectingallthe declaredmethodsoftheclassorinterfacerepresentedbythisClassobject,includingpublic,protected,default(package) access,andprivatemethods,butexcludinginheritedmethods. IfthisClassobjectrepresentsatypethathasmultiple declaredmethodswiththesamenameandparametertypes,butdifferent returntypes,thenthereturnedarrayhasaMethodobjectfor eachsuchmethod. IfthisClassobjectrepresentsatypethathasaclass initializationmethod,thenthereturnedarraydoes nothaveacorrespondingMethodobject. IfthisClassobjectrepresentsaclassorinterfacewithno declaredmethods,thenthereturnedarrayhaslength0. IfthisClassobjectrepresentsanarraytype,aprimitive type,orvoid,thenthereturnedarrayhaslength0. Theelementsinthereturnedarrayarenotsortedandarenotinany particularorder. Returns: thearrayofMethodobjectsrepresentingallthe declaredmethodsofthisclass Throws: SecurityException-Ifasecuritymanager,s,ispresentandanyofthe followingconditionsismet: thecaller'sclassloaderisnotthesameasthe classloaderofthisclassandinvocationof s.checkPermissionmethodwith RuntimePermission("accessDeclaredMembers") deniesaccesstothedeclaredmethodswithinthisclass thecaller'sclassloaderisnotthesameasoran ancestoroftheclassloaderforthecurrentclassand invocationofs.checkPackageAccess()deniesaccesstothepackage ofthisclass Since: JDK1.1 SeeTheJava™LanguageSpecification: 8.2ClassMembers,8.4MethodDeclarations getDeclaredConstructors public Constructor>[] getDeclaredConstructors() throwsSecurityException ReturnsanarrayofConstructorobjectsreflectingallthe constructorsdeclaredbytheclassrepresentedbythis Classobject.Thesearepublic,protected,default (package)access,andprivateconstructors.Theelementsinthearray returnedarenotsortedandarenotinanyparticularorder.Ifthe classhasadefaultconstructor,itisincludedinthereturnedarray. Thismethodreturnsanarrayoflength0ifthisClass objectrepresentsaninterface,aprimitivetype,anarrayclass,or void. SeeTheJavaLanguageSpecification,section8.2. Returns: thearrayofConstructorobjectsrepresentingallthe declaredconstructorsofthisclass Throws: SecurityException-Ifasecuritymanager,s,ispresentandanyofthe followingconditionsismet: thecaller'sclassloaderisnotthesameasthe classloaderofthisclassandinvocationof s.checkPermissionmethodwith RuntimePermission("accessDeclaredMembers") deniesaccesstothedeclaredconstructorswithinthisclass thecaller'sclassloaderisnotthesameasoran ancestoroftheclassloaderforthecurrentclassand invocationofs.checkPackageAccess()deniesaccesstothepackage ofthisclass Since: JDK1.1 getDeclaredField public Field getDeclaredField(String name) throwsNoSuchFieldException, SecurityException ReturnsaFieldobjectthatreflectsthespecifieddeclared fieldoftheclassorinterfacerepresentedbythisClass object.ThenameparameterisaStringthatspecifies thesimplenameofthedesiredfield. IfthisClassobjectrepresentsanarraytype,thenthis methoddoesnotfindthelengthfieldofthearraytype. Parameters: name-thenameofthefield Returns: theFieldobjectforthespecifiedfieldinthis class Throws: NoSuchFieldException-ifafieldwiththespecifiednameis notfound. NullPointerException-ifnameisnull SecurityException-Ifasecuritymanager,s,ispresentandanyofthe followingconditionsismet: thecaller'sclassloaderisnotthesameasthe classloaderofthisclassandinvocationof s.checkPermissionmethodwith RuntimePermission("accessDeclaredMembers") deniesaccesstothedeclaredfield thecaller'sclassloaderisnotthesameasoran ancestoroftheclassloaderforthecurrentclassand invocationofs.checkPackageAccess()deniesaccesstothepackage ofthisclass Since: JDK1.1 SeeTheJava™LanguageSpecification: 8.2ClassMembers,8.3FieldDeclarations getDeclaredMethod public Method getDeclaredMethod(String name, Class>... parameterTypes) throwsNoSuchMethodException, SecurityException ReturnsaMethodobjectthatreflectsthespecified declaredmethodoftheclassorinterfacerepresentedbythis Classobject.Thenameparameterisa Stringthatspecifiesthesimplenameofthedesired method,andtheparameterTypesparameterisanarrayof Classobjectsthatidentifythemethod'sformalparameter types,indeclaredorder.Ifmorethanonemethodwiththesame parametertypesisdeclaredinaclass,andoneofthesemethodshasa returntypethatismorespecificthananyoftheothers,thatmethodis returned;otherwiseoneofthemethodsischosenarbitrarily.Ifthe nameis""or""aNoSuchMethodException israised. IfthisClassobjectrepresentsanarraytype,thenthis methoddoesnotfindtheclone()method. Parameters: name-thenameofthemethod parameterTypes-theparameterarray Returns: theMethodobjectforthemethodofthisclass matchingthespecifiednameandparameters Throws: NoSuchMethodException-ifamatchingmethodisnotfound. NullPointerException-ifnameisnull SecurityException-Ifasecuritymanager,s,ispresentandanyofthe followingconditionsismet: thecaller'sclassloaderisnotthesameasthe classloaderofthisclassandinvocationof s.checkPermissionmethodwith RuntimePermission("accessDeclaredMembers") deniesaccesstothedeclaredmethod thecaller'sclassloaderisnotthesameasoran ancestoroftheclassloaderforthecurrentclassand invocationofs.checkPackageAccess()deniesaccesstothepackage ofthisclass Since: JDK1.1 SeeTheJava™LanguageSpecification: 8.2ClassMembers,8.4MethodDeclarations getDeclaredConstructor public Constructor getDeclaredConstructor(Class>... parameterTypes) throwsNoSuchMethodException, SecurityException ReturnsaConstructorobjectthatreflectsthespecified constructoroftheclassorinterfacerepresentedbythis Classobject.TheparameterTypesparameteris anarrayofClassobjectsthatidentifytheconstructor's formalparametertypes,indeclaredorder. IfthisClassobjectrepresentsaninnerclass declaredinanon-staticcontext,theformalparametertypes includetheexplicitenclosinginstanceasthefirstparameter. Parameters: parameterTypes-theparameterarray Returns: TheConstructorobjectfortheconstructorwiththe specifiedparameterlist Throws: NoSuchMethodException-ifamatchingmethodisnotfound. SecurityException-Ifasecuritymanager,s,ispresentandanyofthe followingconditionsismet: thecaller'sclassloaderisnotthesameasthe classloaderofthisclassandinvocationof s.checkPermissionmethodwith RuntimePermission("accessDeclaredMembers") deniesaccesstothedeclaredconstructor thecaller'sclassloaderisnotthesameasoran ancestoroftheclassloaderforthecurrentclassand invocationofs.checkPackageAccess()deniesaccesstothepackage ofthisclass Since: JDK1.1 getResourceAsStream public InputStream getResourceAsStream(String name) Findsaresourcewithagivenname.Therulesforsearchingresources associatedwithagivenclassareimplementedbythedefining classloaderoftheclass.Thismethod delegatestothisobject'sclassloader.Ifthisobjectwasloadedby thebootstrapclassloader,themethoddelegatestoClassLoader.getSystemResourceAsStream(java.lang.String). Beforedelegation,anabsoluteresourcenameisconstructedfromthe givenresourcenameusingthisalgorithm: Ifthenamebeginswitha'/' ('\u002f'),thentheabsolutenameoftheresourceisthe portionofthenamefollowingthe'/'. Otherwise,theabsolutenameisofthefollowingform: modified_package_name/name Wherethemodified_package_nameisthepackagenameofthis objectwith'/'substitutedfor'.' ('\u002e'). Parameters: name-nameofthedesiredresource Returns: AInputStreamobjectornullif noresourcewiththisnameisfound Throws: NullPointerException-Ifnameisnull Since: JDK1.1 getResource public URL getResource(String name) Findsaresourcewithagivenname.Therulesforsearchingresources associatedwithagivenclassareimplementedbythedefining classloaderoftheclass.Thismethod delegatestothisobject'sclassloader.Ifthisobjectwasloadedby thebootstrapclassloader,themethoddelegatestoClassLoader.getSystemResource(java.lang.String). Beforedelegation,anabsoluteresourcenameisconstructedfromthe givenresourcenameusingthisalgorithm: Ifthenamebeginswitha'/' ('\u002f'),thentheabsolutenameoftheresourceisthe portionofthenamefollowingthe'/'. Otherwise,theabsolutenameisofthefollowingform: modified_package_name/name Wherethemodified_package_nameisthepackagenameofthis objectwith'/'substitutedfor'.' ('\u002e'). Parameters: name-nameofthedesiredresource Returns: AURLobjectornullifno resourcewiththisnameisfound Since: JDK1.1 getProtectionDomain public ProtectionDomain getProtectionDomain() ReturnstheProtectionDomainofthisclass.Ifthereisa securitymanagerinstalled,thismethodfirstcallsthesecurity manager'scheckPermissionmethodwitha RuntimePermission("getProtectionDomain")permissionto ensureit'soktogetthe ProtectionDomain. Returns: theProtectionDomainofthisclass Throws: SecurityException-ifasecuritymanagerexistsandits checkPermissionmethoddoesn'tallow gettingtheProtectionDomain. Since: 1.2 SeeAlso: ProtectionDomain, SecurityManager.checkPermission(java.security.Permission), RuntimePermission desiredAssertionStatus public boolean desiredAssertionStatus() Returnstheassertionstatusthatwouldbeassignedtothis classifitweretobeinitializedatthetimethismethodisinvoked. Ifthisclasshashaditsassertionstatusset,themostrecent settingwillbereturned;otherwise,ifanypackagedefaultassertion statuspertainstothisclass,themostrecentsettingforthemost specificpertinentpackagedefaultassertionstatusisreturned; otherwise,ifthisclassisnotasystemclass(i.e.,ithasa classloader)itsclassloader'sdefaultassertionstatusisreturned; otherwise,thesystemclassdefaultassertionstatusisreturned. Fewprogrammerswillhaveanyneedforthismethod;itisprovided forthebenefitoftheJREitself.(Itallowsaclasstodetermineat thetimethatitisinitializedwhetherassertionsshouldbeenabled.) Notethatthismethodisnotguaranteedtoreturntheactual assertionstatusthatwas(orwillbe)associatedwiththespecified classwhenitwas(orwillbe)initialized. Returns: thedesiredassertionstatusofthespecifiedclass. Since: 1.4 SeeAlso: ClassLoader.setClassAssertionStatus(java.lang.String,boolean), ClassLoader.setPackageAssertionStatus(java.lang.String,boolean), ClassLoader.setDefaultAssertionStatus(boolean) isEnum public boolean isEnum() Returnstrueifandonlyifthisclasswasdeclaredasanenuminthe sourcecode. Returns: trueifandonlyifthisclasswasdeclaredasanenuminthe sourcecode Since: 1.5 getEnumConstants public T[] getEnumConstants() Returnstheelementsofthisenumclassornullifthis Classobjectdoesnotrepresentanenumtype. Returns: anarraycontainingthevaluescomprisingtheenumclass representedbythisClassobjectintheorderthey're declared,ornullifthisClassobjectdoesnot representanenumtype Since: 1.5 cast public T cast(Object obj) Castsanobjecttotheclassorinterfacerepresented bythisClassobject. Parameters: obj-theobjecttobecast Returns: theobjectaftercasting,ornullifobjisnull Throws: ClassCastException-iftheobjectisnot nullandisnotassignabletothetypeT. Since: 1.5 asSubclass public  Class asSubclass(Class clazz) CaststhisClassobjecttorepresentasubclassoftheclass representedbythespecifiedclassobject.Checksthatthecast isvalid,andthrowsaClassCastExceptionifitisnot.If thismethodsucceeds,italwaysreturnsareferencetothisclassobject. Thismethodisusefulwhenaclientneedsto"narrow"thetypeof aClassobjecttopassittoanAPIthatrestrictsthe Classobjectsthatitiswillingtoaccept.Acastwould generateacompile-timewarning,asthecorrectnessofthecast couldnotbecheckedatruntime(becausegenerictypesareimplemented byerasure). TypeParameters: U-thetypetocastthisclassobjectto Parameters: clazz-theclassofthetypetocastthisclassobjectto Returns: thisClassobject,casttorepresentasubclassof thespecifiedclassobject. Throws: ClassCastException-ifthisClassobjectdoesnot representasubclassofthespecifiedclass(here"subclass"includes theclassitself). Since: 1.5 getAnnotation public  A getAnnotation(Class annotationClass) Descriptioncopiedfrominterface: AnnotatedElement Returnsthiselement'sannotationforthespecifiedtypeif suchanannotationispresent,elsenull. Specifiedby: getAnnotation ininterface AnnotatedElement TypeParameters: A-thetypeoftheannotationtoqueryforandreturnifpresent Parameters: annotationClass-theClassobjectcorrespondingtothe annotationtype Returns: thiselement'sannotationforthespecifiedannotationtypeif presentonthiselement,elsenull Throws: NullPointerException-ifthegivenannotationclassisnull Since: 1.5 isAnnotationPresent public boolean isAnnotationPresent(Class annotationClass) Returnstrueifanannotationforthespecifiedtype ispresentonthiselement,elsefalse.Thismethod isdesignedprimarilyforconvenientaccesstomarkerannotations. Thetruthvaluereturnedbythismethodisequivalentto: getAnnotation(annotationClass)!=null Thebodyofthedefaultmethodisspecifiedtobethecode above. Specifiedby: isAnnotationPresent ininterface AnnotatedElement Parameters: annotationClass-theClassobjectcorrespondingtothe annotationtype Returns: trueifanannotationforthespecifiedannotation typeispresentonthiselement,elsefalse Throws: NullPointerException-ifthegivenannotationclassisnull Since: 1.5 getAnnotationsByType public  A[] getAnnotationsByType(Class annotationClass) Descriptioncopiedfrominterface: AnnotatedElement Returnsannotationsthatareassociatedwiththiselement. Iftherearenoannotationsassociatedwiththiselement,thereturn valueisanarrayoflength0. ThedifferencebetweenthismethodandAnnotatedElement.getAnnotation(Class) isthatthismethoddetectsifitsargumentisarepeatable annotationtype(JLS9.6),andifso,attemptstofindoneor moreannotationsofthattypeby"lookingthrough"acontainer annotation. Thecallerofthismethodisfreetomodifythereturnedarray;itwill havenoeffectonthearraysreturnedtoothercallers. Specifiedby: getAnnotationsByType ininterface AnnotatedElement TypeParameters: A-thetypeoftheannotationtoqueryforandreturnifpresent Parameters: annotationClass-theClassobjectcorrespondingtothe annotationtype Returns: allthiselement'sannotationsforthespecifiedannotationtypeif associatedwiththiselement,elseanarrayoflengthzero Throws: NullPointerException-ifthegivenannotationclassisnull Since: 1.8 getAnnotations public Annotation[] getAnnotations() Descriptioncopiedfrominterface: AnnotatedElement Returnsannotationsthatarepresentonthiselement. Iftherearenoannotationspresentonthiselement,thereturn valueisanarrayoflength0. Thecallerofthismethodisfreetomodifythereturnedarray;itwill havenoeffectonthearraysreturnedtoothercallers. Specifiedby: getAnnotations ininterface AnnotatedElement Returns: annotationspresentonthiselement Since: 1.5 getDeclaredAnnotation public  A getDeclaredAnnotation(Class annotationClass) Descriptioncopiedfrominterface: AnnotatedElement Returnsthiselement'sannotationforthespecifiedtypeif suchanannotationisdirectlypresent,elsenull. Thismethodignoresinheritedannotations.(Returnsnullifno annotationsaredirectlypresentonthiselement.) Specifiedby: getDeclaredAnnotation ininterface AnnotatedElement TypeParameters: A-thetypeoftheannotationtoqueryforandreturnifdirectlypresent Parameters: annotationClass-theClassobjectcorrespondingtothe annotationtype Returns: thiselement'sannotationforthespecifiedannotationtypeif directlypresentonthiselement,elsenull Throws: NullPointerException-ifthegivenannotationclassisnull Since: 1.8 getDeclaredAnnotationsByType public  A[] getDeclaredAnnotationsByType(Class annotationClass) Descriptioncopiedfrominterface: AnnotatedElement Returnsthiselement'sannotation(s)forthespecifiedtypeif suchannotationsareeitherdirectlypresentor indirectlypresent.Thismethodignoresinherited annotations. Iftherearenospecifiedannotationsdirectlyorindirectly presentonthiselement,thereturnvalueisanarrayoflength 0. ThedifferencebetweenthismethodandAnnotatedElement.getDeclaredAnnotation(Class)isthatthismethoddetectsifits argumentisarepeatableannotationtype(JLS9.6),andifso, attemptstofindoneormoreannotationsofthattypeby"looking through"acontainerannotationifoneispresent. Thecallerofthismethodisfreetomodifythereturnedarray;itwill havenoeffectonthearraysreturnedtoothercallers. Specifiedby: getDeclaredAnnotationsByType ininterface AnnotatedElement TypeParameters: A-thetypeoftheannotationtoqueryforandreturn ifdirectlyorindirectlypresent Parameters: annotationClass-theClassobjectcorrespondingtothe annotationtype Returns: allthiselement'sannotationsforthespecifiedannotationtypeif directlyorindirectlypresentonthiselement,elseanarrayoflengthzero Throws: NullPointerException-ifthegivenannotationclassisnull Since: 1.8 getDeclaredAnnotations public Annotation[] getDeclaredAnnotations() Descriptioncopiedfrominterface: AnnotatedElement Returnsannotationsthataredirectlypresentonthiselement. Thismethodignoresinheritedannotations. Iftherearenoannotationsdirectlypresentonthiselement, thereturnvalueisanarrayoflength0. Thecallerofthismethodisfreetomodifythereturnedarray;itwill havenoeffectonthearraysreturnedtoothercallers. Specifiedby: getDeclaredAnnotations ininterface AnnotatedElement Returns: annotationsdirectlypresentonthiselement Since: 1.5 getAnnotatedSuperclass public AnnotatedType getAnnotatedSuperclass() ReturnsanAnnotatedTypeobjectthatrepresentstheuseofa typetospecifythesuperclassoftheentityrepresentedbythisClassobject.(TheuseoftypeFootospecifythesuperclass in'...extendsFoo'isdistinctfromthedeclarationoftype Foo.) IfthisClassobjectrepresentsatypewhosedeclaration doesnotexplicitlyindicateanannotatedsuperclass,thenthereturn valueisanAnnotatedTypeobjectrepresentinganelementwithno annotations. IfthisClassrepresentseithertheObjectclass,an interfacetype,anarraytype,aprimitivetype,orvoid,thereturn valueisnull. Returns: anobjectrepresentingthesuperclass Since: 1.8 getAnnotatedInterfaces public AnnotatedType[] getAnnotatedInterfaces() ReturnsanarrayofAnnotatedTypeobjectsthatrepresenttheuse oftypestospecifysuperinterfacesoftheentityrepresentedbythis Classobject.(TheuseoftypeFootospecifya superinterfacein'...implementsFoo'isdistinctfromthe declarationoftypeFoo.) IfthisClassobjectrepresentsaclass,thereturnvalueis anarraycontainingobjectsrepresentingtheusesofinterfacetypesto specifyinterfacesimplementedbytheclass.Theorderoftheobjectsin thearraycorrespondstotheorderoftheinterfacetypesusedinthe 'implements'clauseofthedeclarationofthisClassobject. IfthisClassobjectrepresentsaninterface,thereturn valueisanarraycontainingobjectsrepresentingtheusesofinterface typestospecifyinterfacesdirectlyextendedbytheinterface.The orderoftheobjectsinthearraycorrespondstotheorderofthe interfacetypesusedinthe'extends'clauseofthedeclarationofthis Classobject. IfthisClassobjectrepresentsaclassorinterfacewhose declarationdoesnotexplicitlyindicateanyannotatedsuperinterfaces, thereturnvalueisanarrayoflength0. IfthisClassobjectrepresentseithertheObject class,anarraytype,aprimitivetype,orvoid,thereturnvalueisan arrayoflength0. Returns: anarrayrepresentingthesuperinterfaces Since: 1.8 Skipnavigationlinks Overview Package Class Use Tree Deprecated Index Help Java™ PlatformStandard Ed. 8 Prev Class Next Class Frames No Frames All Classes Summary:  Nested |  Field |  Constr |  Method Detail:  Field |  Constr |  Method SubmitabugorfeatureForfurtherAPIreferenceanddeveloperdocumentation,seeJavaSEDocumentation.Thatdocumentationcontainsmoredetailed,developer-targeteddescriptions,withconceptualoverviews,definitionsofterms,workarounds,andworkingcodeexamples.Copyright©1993,2022,Oracleand/oritsaffiliates.Allrightsreserved.Useissubjecttolicenseterms.Alsoseethedocumentationredistributionpolicy.



請為這篇文章評分?