Java.lang.Class class in Java | Set 1
More methods:
- int getModifiers() : This method returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine’s constants for public, protected, private, final, static, abstract and interface. These modifiers are already decoded in Modifier class in java.lang.Reflect package.
Syntax : public int getModifiers() Parameters : NA Returns : the int representing the modifiers for this class
// Java program to demonstrate getModifiers() methodimportjava.lang.reflect.Modifier;publicabstractclassTest{publicstaticvoidmain(String[] args){// returns the Class object associated with Test classClass c = Test.class;// returns the Modifiers of the class Test// getModifiers methodinti = c.getModifiers();System.out.println(i);System.out.print("Modifiers of "+ c.getName() +" class are : ");// getting decoded i using toString() method// of Modifier classSystem.out.println(Modifier.toString(i));}}Output:
1025 Modifiers of Test class are : public abstract
- T[] getEnumConstants() : This method returns the elements of this enum class. It returns null if this Class object does not represent an enum type.
Syntax : public T[] getEnumConstants() Parameters : NA Returns : an array containing the values comprising the enum class represented by this Class object in the order they're declared, or null if this Class object does not represent an enum type
// Java program to demonstrate getEnumConstants() methodenumColor{RED, GREEN, BLUE;}publicclassTest{publicstaticvoidmain(String[] args){// returns the Class object associated with Color(an enum class)Class c1 = Color.class;// returns the Class object associated with Test classClass c2 = Test.class;// returns the elements of Color enum class in an array// getEnumConstants methodObject[] obj1 = c1.getEnumConstants();System.out.println("Enum constants of "+ c1.getName() +" class are :");// iterating through enum constantsfor(Object object : obj1){System.out.println(object);}// returns null as Test Class object does not represent an enum typeObject[] obj2 = c2.getEnumConstants();System.out.println("Test class does not contain any Enum constant.");System.out.println(obj2);}}Output:
Enum constants of Color class are : RED GREEN BLUE Test class does not contain any Enum constant. null
- String getCanonicalName() : This method returns the canonical name of the underlying class as defined by the Java Language Specification.
It returns null if the underlying class does not have a canonical name (i.e., if it is a local or anonymous class or an array whose component type does not have a canonical name).Syntax : public String getCanonicalName() Parameters : NA Returns : the Canonical name of the underlying class, if it exists null, otherwise
// Java program to demonstrate getCanonicalName() methodpublicclassTest{publicstaticvoidmain(String[] args)throwsClassNotFoundException{// returns the Class object for the class// with the specified nameClass c1 = Class.forName("java.lang.String");System.out.print("Canonical name of class represented by c1 : ");// returns the Canonical name of the class// getCanonicalName methodSystem.out.println(c1.getCanonicalName());}}Output:
Canonical name of class represented by c1 : java.lang.String
- boolean desiredAssertionStatus() : This method returns the assertion status that would be assigned to this class if it were to be initialized at the time this method is invoked.
Syntax : public boolean desiredAssertionStatus() Parameters : NA Returns : the desired assertion status of the specified class.
// Java program to demonstrate desiredAssertionStatus() methodpublicclassTest{publicstaticvoidmain(String[] args)throwsClassNotFoundException{// returns the Class object for the class// with the specified nameClass c1 = Class.forName("java.lang.String");// checking for assertion status of String classSystem.out.print("desired assertion status of "+ c1.getName() +"class: ");// desiredAssertionStatus() methodSystem.out.println(c1.desiredAssertionStatus());}}Output:
desired assertion status of java.lang.Stringclass : false
- Class<?> getComponentType() : This method returns the Class representing the component type of an array. If this class does not represent an array class this method returns null.
Syntax : public Class<?> getComponentType() Parameters : NA Returns : the Class representing the component type of this class if this class is an array
// Java program to demonstrate getComponentType() methodpublicclassTest{publicstaticvoidmain(String[] args){inta[] =newint[2];// returns the Class object for array classClass c = a.getClass();System.out.print("Component type of class represented by c : ");// getComponentType() methodSystem.out.println(c.getComponentType());}}Output:
Component type of class represented by c : int
- Class<?>[] getDeclaredClasses() : Returns an array of Class objects reflecting all the classes and interfaces declared as members of the class represented by this Class object.
This method includes public, protected, default (package) access, and private classes and interfaces declared by the class, but excludes inherited classes and interfaces. This method returns an array of length 0 if the class declares no classes or interfaces as members, or if this Class object represents a primitive type, an array class, or void.Syntax : public Class<?>[] getDeclaredClasses() Parameters : NA Returns : the array of Class objects representing all the declared members of this class Throws : SecurityException - If a security manager, s, is present
// Java program to demonstrate getDeclaredClasses() methodpublicclassTest{// base interfaceinterfaceA{// methods and constant declarations}// derived classclassBimplementsA{// methods implementations that were declared in A}publicstaticvoidmain(String[] args){// returns the Class object associated with Test classClass myClass = Test.class;// getDeclaredClasses on myClass// it returns array of classes and interface declare in Test classClass c[] = myClass.getDeclaredClasses();System.out.println("Declared classes and interfaces present in "+myClass.getName() +" class : ");// iterating through classes and interfaces declared in Test classfor(Class class1 : c){System.out.println(class1);}}}Output:
Declared classes and interfaces present in Test class : interface Test$A class Test$B
- Field getDeclaredField(String fieldName) : This method returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.
The name parameter is a String that specifies the simple name of the desired field. Note that this method will not reflect the length field of an array class.Syntax : public Field getDeclaredField(String fieldName) throws NoSuchFieldException,SecurityException Parameters : fieldName - the field name Returns : the Field object for the specified field in this class Throws : NoSuchFieldException - if a field with the specified name is not found. NullPointerException - if fieldName is null SecurityException - If a security manager, s, is present.
// Java program to demonstrate getDeclaredField() methodimportjava.lang.reflect.Field;publicclassTest{// any declared fieldinti;publicstaticvoidmain(String[] args)throwsNoSuchFieldException, SecurityException{// returns the Class object associated with Test classClass myClass = Test.class;// getDeclaredField on myClassField f = myClass.getDeclaredField("i");System.out.println("Declared field present in "+myClass.getName() +" class specified by \"i\" : ");System.out.println(f);}}Output:
Declared field present in Test class specified by "i" : int Test.i
- Field[] getDeclaredFields() : This method returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes inherited fields.
This method returns an array of length 0 if the class or interface declares no fields, or if this Class object represents a primitive type, an array class, or void.
Syntax : public Field[] getDeclaredFields() throws SecurityException Parameters : NA Returns : the array of Field objects representing all the declared fields of this class Throws : SecurityException - If a security manager, s, is present.
// Java program to demonstrate getDeclaredFields() methodimportjava.lang.reflect.Field;publicclassTest{// some declared fieldsinti;String str;booleanb;publicstaticvoidmain(String[] args){// returns the Class object associated with Test classClass myClass = Test.class;// getDeclaredFields on myClassField f[] = myClass.getDeclaredFields();System.out.println("Declared fields present in "+myClass.getName() +" class are : ");// iterating through declared fields of Test classfor(Field field : f){System.out.println(field);}}}Output:
Declared fields present in Test class are : int Test.i java.lang.String Test.str boolean Test.b
- Method getDeclaredMethod(String methodName,Class… parameterTypes) : This method returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.
Syntax : public Method getDeclaredMethod(String methodName,Class... parameterTypes) throws NoSuchFieldException,SecurityException Parameters : methodName - the method name parameterTypes - the list of parameters Returns : the Method object for the method of this class matching the specified name and parameters Throws : NoSuchMethodException - if a method with the specified name is not found. NullPointerException - if methodName is null SecurityException - If a security manager, s, is present.
// Java program to demonstrate getDeclaredMethod() methodimportjava.lang.reflect.Method;publicclassTest{// any declared method// with a String argumentpublicvoidm1(String str){System.out.println(str);}publicstaticvoidmain(String[] args)throwsNoSuchMethodException, SecurityException, ClassNotFoundException{// returns the Class object associated with Test classClass myClass = Test.class;// returns the Class object for the class// with the specified nameClass c = Class.forName("java.lang.String");// getDeclaredMethod on myClassMethod m = myClass.getDeclaredMethod("m1",c);System.out.println("Declared method present in "+myClass.getName() +" class specified by argument : "+ c.getName());System.out.println(m);}}Output:
Declared method present in Test class specified by argument : java.lang.String public void Test.m1(java.lang.String)
- Method[] getDeclaredMethods() : This method retuns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private methods, but excludes inherited methods.
This method returns an array of length 0 if the class or interface declares no methods, or if this Class object represents a primitive type, an array class, or void.
Syntax : public Method[] getDeclaredMethods() throws SecurityException Parameters : NA Returns : the array of Method objects representing all the declared methods of this class Throws : SecurityException - If a security manager, s, is present.
// Java program to demonstrate getDeclaredMethods() methodimportjava.lang.reflect.Method;publicclassTest{// some declared Methodspublicvoidm1(){System.out.println("Inside m1 method");}staticvoidm2(){System.out.println("Inside m2 method");}// main methodpublicstaticvoidmain(String[] args){// returns the Class object associated with Test classClass myClass = Test.class;// getDeclaredMethods on myClassMethod m[] = myClass.getDeclaredMethods();System.out.println("Declared methods present in "+myClass.getName() +" class are : ");// iterating through declared Methods of Test classfor(Method Method : m){System.out.println(Method);}}}Output:
Declared methods present in Test class are : public static void Test.main(java.lang.String[]) public void Test.m1() static void Test.m2()
- Constructor<?> getDeclaredConstructor(Class<?>… parameterTypes) : This method returns a Constructor object that reflects the specified constructor of the class or interface represented by this Class object.
Syntax : public Constructor<?> getDeclaredConstructor(Class<?>... parameterTypes) throws NoSuchMethodException,SecurityException Parameters : parameterTypes - the list of parameters Returns : The Constructor object for the constructor with the specified parameter list Throws : NoSuchMethodException - if a Constructor with the specified parameterTypes is not found. SecurityException - If a security manager, s, is present.
// Java program to demonstrate getDeclaredConstructor() Constructorimportjava.lang.reflect.Constructor;publicclassTest{publicstaticvoidmain(String[] args)throwsNoSuchMethodException, SecurityException, ClassNotFoundException{// returns the Class object for the class// with the specified nameClass c1 = Class.forName("java.lang.Integer");Class c2 = Class.forName("java.lang.String");// getDeclaredConstructor on myClassConstructor con = c1.getDeclaredConstructor(c2);System.out.println("Declared Constructor present in "+ c1.getName() +" class specified by argument : "+ c2.getName());System.out.println(con);}}Output:
Declared Constructor present in java.lang.Integer class specified by argument : java.lang.String public java.lang.Integer(java.lang.String) throws java.lang.NumberFormatException
- Constructor<?>[] getDeclaredConstructors() : This method returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object. These are public, protected, default (package) access, and private constructors.
This method returns an array of length 0 if this Class object represents an interface, a primitive type, an array class, or void.
Syntax : public Constructor<?>[] getDeclaredConstructors() throws SecurityException Parameters : NA Returns : the array of Constructor objects representing all the declared constructors of this class Throws : SecurityException - If a security manager, s, is present.
// Java program to demonstrate getDeclaredConstructors() Constructorimportjava.lang.reflect.Constructor;publicclassTest{publicstaticvoidmain(String[] args)throwsClassNotFoundException{// returns the Class object for the class// with the specified nameClass c = Class.forName("java.lang.String");// getDeclaredConstructors on myClassConstructor con[] = c.getDeclaredConstructors();System.out.println("Declared Constructors present in "+c.getName() +" class are : ");// iterating through all constructorsfor(Constructor constructor : con){System.out.println(constructor);}}}Output:
Declared Constructors present in java.lang.String class are : public java.lang.String(byte[],int,int) public java.lang.String(byte[],java.nio.charset.Charset) public java.lang.String(byte[],java.lang.String) throws java.io.UnsupportedEncodingException public java.lang.String(byte[],int,int,java.nio.charset.Charset) public java.lang.String(byte[],int,int,java.lang.String) throws java.io.UnsupportedEncodingException java.lang.String(char[],boolean) public java.lang.String(java.lang.StringBuilder) public java.lang.String(java.lang.StringBuffer) public java.lang.String(byte[]) public java.lang.String(int[],int,int) public java.lang.String() public java.lang.String(char[]) public java.lang.String(java.lang.String) public java.lang.String(char[],int,int) public java.lang.String(byte[],int) public java.lang.String(byte[],int,int,int)
- Class<?> getDeclaringClass() : If the class or interface represented by this Class object is a member of another class, then this method returns the Class object representing the class in which it was declared.
This method returns null if this class or interface is not a member of any other class. If this Class object represents an array class, a primitive type, or void,then this method returns null.
Syntax : public Class<?> getDeclaringClass() Parameters : NA Returns : the declaring class of this class
// Java program to demonstrate// getDeclaringClass() Classimportjava.lang.reflect.Method;publicclassTest{// any methodpublicvoidm1(){System.out.println("Inside m1 method");}publicstaticvoidmain(String[] args){// returns A class objectClass c1 = Test.class;// getting all methods of Test class// Note that methods from Object class// are also inheritedMethod m[] = c1.getMethods();for(Method method : m){// getDeclaringClass method// it return declared class of this methodSystem.out.println(method.getName() +" is present in "+ method.getDeclaringClass());}}}Output:
main is present in class Test m1 is present in class Test wait is present in class java.lang.Object wait is present in class java.lang.Object wait is present in class java.lang.Object equals is present in class java.lang.Object toString is present in class java.lang.Object hashCode is present in class java.lang.Object getClass is present in class java.lang.Object notify is present in class java.lang.Object notifyAll is present in class java.lang.Object
- Class<?> getEnclosingClass() : This method returns the immediately enclosing class of the underlying class. If the underlying class is a top level class this method returns null.
Syntax : public Class<?> getEnclosingClass() Parameters : NA Returns : the immediately enclosing class of the underlying class
// Java program to demonstrate getEnclosingClass() ClasspublicclassTest{// any inner class of Test classclassA{}publicstaticvoidmain(String[] args){// returns A class objectClass c1 = Test.A.class;// getEnclosingClass method// it returns the class object where A class presentClass c2 = c1.getEnclosingClass();System.out.println("The class "+ c1.getName() +" is present in class : ");System.out.println(c2);}}Output:
The class Test$A is present in class : class Test
- Method getEnclosingMethod() : If this Class object represents a local or anonymous class within a method, returns a Method object representing the immediately enclosing method of the underlying class.
Syntax : public Class<?> getEnclosingMethod() Parameters : NA Returns : the immediately enclosing method of the underlying class, if that class is a local or anonymous class; otherwise null
// Java program to demonstrate getEnclosingMethod() methodimportjava.lang.reflect.Method;publicclassTest{// any methodpublicstaticClass m1(){// any local class in m1classA{};// returning class AreturnA.class;}// main methodpublicstaticvoidmain(String[] args)throwsClassNotFoundException{// returns A Class objectClass c = Test.m1();// getEnclosingMethod methodMethod m = c.getEnclosingMethod();System.out.println("The class "+ c.getName() +" is present in method : ");System.out.println(m);}}Output:
The class Test$1A is present in method : public static java.lang.Class Test.m1()
- Constructor getEnclosingConstructor() : If this Class object represents a local or anonymous class within a constructor, returns a Constructor object representing the immediately enclosing constructor of the underlying class. Returns null otherwise.
Syntax : public Constructor<?> getEnclosingConstructor() Parameters : NA Returns : the immediately enclosing constructor of the underlying class, if that class is a local or anonymous class; otherwise null.
// Java program to demonstrate// getEnclosingConstructor() Constructorimportjava.lang.reflect.Constructor;publicclassTest{Class c;// default(any) constructorpublicTest(){// any local classclassA{};// returns A class objectc = A.class;}publicstaticvoidmain(String[] args){// creating Test class objectTest t =newTest();// getEnclosingConstructor methodConstructor con = t.c.getEnclosingConstructor();System.out.println("The class "+ t.c.getName()+" is present in constructor : ");System.out.println(con);}}Output:
The class Test$1A is present in Constructor : public Test()
- ProtectionDomain getProtectionDomain() : Returns the ProtectionDomain of this class. If there is a security manager installed, this method first calls the security manager’s checkPermission method with a RuntimePermission(“getProtectionDomain”) permission to ensure it’s ok to get the ProtectionDomain.
Syntax : public ProtectionDomain getProtectionDomain() Parameters : NA Returns : the ProtectionDomain of this class Throws : SecurityException - if a security manager s exists and its checkPermission method doesn't allow getting the ProtectionDomain.
// Java program to demonstrate getProtectionDomain() methodpublicclassTest{publicstaticvoidmain(String[] args)throwsClassNotFoundException{// returns the Class object for the class// with the specified nameClass c1 = Class.forName("java.lang.String");// checking for assertion status of String classSystem.out.println("protection domain of "+ c1.getName() +" class : ");// getProtectionDomain() method// it will print null as String class is loaded by// BootStrap class loaderSystem.out.println(c1.getProtectionDomain());}}Output:
protection domain of java.lang.String class : ProtectionDomain null null java.security.Permissions@7852e922 ( ("java.security.AllPermission" "" "") ) - boolean isAnnotationPresent(Class<?extends Annotation> annotationClass)() : This method returns true if an annotation for the specified type is present on this element, else false. This method is designed primarily for convenient access to marker annotations.
Specified by: isAnnotationPresent in interface AnnotatedElement Syntax : public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) Parameters : annotationClass - the Class object corresponding to the annotation type Returns : true if an annotation for the specified annotation type is present on this element false, otherwise Throws: NullPointerException - if the given annotation class is null
- boolean isSynthetic() : This method determines if this class is a synthetic class or not.
Syntax : public boolean isSynthetic() Parameters : NA Returns : return true if and only if this class is a synthetic class.
- URL getResource(String name) : Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class.
Syntax : public URL getResource(String name) Parameters : name - name of the desired resource Returns : A URL object or null if no resource with this name is found
- InputStream getResourceAsStream(String name) : Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class.
Syntax : public InputStream getResourceAsStream(String name) Parameters : name - name of the desired resource Returns : A InputStream object or null if no resource with this name is found Throws: NullPointerException - If name is null
- Object[] getSigners() : Gets the signers of this class.
Syntax : public Object[] getSigners() Parameters : NA Returns : the signers of this class, or null if there are no signers. In particular,it returns null if this object represents a primitive type or void.
- Annotation[] getAnnotations() : This method returns all annotations present on this element. It returns an array of length zero if this element has no annotations.
The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.Specified by: getAnnotations() in interface AnnotatedElement Syntax : public Annotation[] getAnnotations() Parameters : NA Returns : all annotations present on this element
- <A extends Annotation> A getAnnotation(Class<A> annotationClass) : This method returns this element’s annotation for the specified type if such an annotation is present, else null.
Specified by: getAnnotations() in interface AnnotatedElement Syntax : public Annotation[] getAnnotations() Parameters : annotationClass - the Class object corresponding to the annotation type Returns : return element's annotation for the specified annotation type if present on this element else null Throws: NullPointerException - if the given annotation class is null
- Annotation[] getDeclaredAnnotations() : Returns all annotations that are directly present on this element. Unlike the other methods in this interface, this method ignores inherited annotations. It returns an array of length zero if no annotations are directly present on this element.
The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers.Specified by: getDeclaredAnnotations in interface AnnotatedElement Syntax : public Annotation[] getDeclaredAnnotations() Parameters : NA Returns : All annotations directly present on this element
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.



