Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are constructed automatically by the Java Virtual Machine(JVM). It is a final class, so we cannot extend it. The Class class methods are widely used in Reflection API.
In Java, the java.lang.Class class is a built-in class that represents a class or interface at runtime. It contains various methods that provide information about the class or interface, such as its name, superclass, interfaces, fields, and methods.
Here are some commonly used methods of the Class class:
getName(): Returns the name of the class or interface represented by this Class object.
getSimpleName(): Returns the simple name of the class or interface represented by this Class object.
getSuperclass(): Returns the superclass of the class represented by this Class object.
getInterfaces(): Returns an array of interfaces implemented by the class or interface represented by this Class object.
getField(String name): Returns a Field object that represents the public field with the specified name in the class or interface represented by this Class object.
getMethod(String name, Class<?>… parameterTypes): Returns a Method object that represents the public method with the specified name and parameter types in the class or interface represented by this Class object.
newInstance(): Creates a new instance of the class represented by this Class object using its default constructor.
isInstance(Object obj): Returns true if the specified object is an instance of the class or interface represented by this Class object, false otherwise.
isAssignableFrom(Class<?> cls): Returns true if this Class object is assignable from the specified Class object, false otherwise.
Here’s an example of how to use some of these methods:
System.out.println("Is string assignable from Object? "+ String.class.isAssignableFrom(Object.class));
}
}
Output:
Name: java.lang.String
Simple name: String
Superclass: class java.lang.Object
Interfaces: []
Is string assignable from Object? true
Creating a Class object
There are three ways to create Class object :
Class.forName(“className”) : Since class Class doesn’t contain any constructor, there is static factory method present in class Class, which is Class.forName() , used for creating object of class Class. Below is the syntax :
Class c = Class.forName(String className)
The above statement creates the Class object for the class passed as a String argument(className). Note that the parameter className must be fully qualified name of the desired class for which Class object is to be created. The methods in any class in java which returns the same class object are also known as factory methods. The class name for which Class object is to be created is determined at run-time.
Myclass.class : When we write .class after a class name, it references the Class object that represents the given class. It is mostly used with primitive data types and only when we know the name of class. The class name for which Class object is to be created is determined at compile-time. Below is the syntax :
Class c = int.class
Please note that this method is used with class name, not with class instances. For example
A a = new A(); // Any class A
Class c = A.class; // No error
Class c = a.class; // Error
obj.getClass(): This method is present in Object class. It return the run-time class of this(obj) object. Below is the syntax :
A a = new A(); // Any class A
Class c = a.getClass();
Methods:
String toString() : This method converts the Class object to a string. It returns the string representation which is the string “class” or “interface”, followed by a space, and then by the fully qualified name of the class. If the Class object represents a primitive type, then this method returns the name of the primitive type and if it represents void then it returns “void”.
Syntax :
public String toString()
Parameters :
NA
Returns :
a string representation of this class object.
Overrides :
toString in class Object
Java
// Java program to demonstrate toString() method
publicclassTest {
publicstaticvoidmain(String[] args)
throwsClassNotFoundException
{
// returns the Class object for the class
// with the specified name
Class c1 = Class.forName("
java.lang.String & quot;);
Class c2 = int.class;
Class c3 = void.class;
System.out.print(" Class represented by c1
: ");
// toString method on c1
System.out.println(c1.toString());
System.out.print(" Class represented by c2
: ");
// toString method on c2
System.out.println(c2.toString());
System.out.print(" Class represented by c3
: ");
// toString method on c3
System.out.println(c3.toString());
}
}
Output:
Class represented by c1: class java.lang.String
Class represented by c2: int
Class represented by c3: void
Class<?> forName(String className) : As discussed earlier, this method returns the Class object associated with the class or interface with the given string name. The other variant of this method is discussed next.
Syntax :
public static Class<?> forName(String className) throws ClassNotFoundException
Parameters :
className - the fully qualified name of the desired class.
Returns :
return the Class object for the class with the specified name.
Throws :
LinkageError : if the linkage fails
ExceptionInInitializerError - if the initialization provoked by this method fails
ClassNotFoundException - if the class cannot be located
Java
// Java program to demonstrate forName() method
publicclassTest
{
publicstaticvoidmain(String[] args)
throwsClassNotFoundException
{
// forName method
// it returns the Class object for the class
// with the specified name
Class c = Class.forName("java.lang.String");
System.out.print("Class represented by c : " + c.toString());
}
}
Output:
Class represented by c : class java.lang.String
Class<?> forName(String className,boolean initialize, ClassLoader loader) : This method also returns the Class object associated with the class or interface with the given string name using the given class loader. The specified class loader is used to load the class or interface. If the parameter loader is null, the class is loaded through the bootstrap class loader in. The class is initialized only if the initialize parameter is true and if it has not been initialized earlier.
Syntax :
public static Class<?> forName(String className,boolean initialize, ClassLoader loader)
throws ClassNotFoundException
Parameters :
className - the fully qualified name of the desired class
initialize - whether the class must be initialized
loader - class loader from which the class must be loaded
Returns :
return the Class object for the class with the specified name.
Throws :
LinkageError : if the linkage fails
ExceptionInInitializerError - if the initialization provoked by this method fails
ClassNotFoundException - if the class cannot be located
Example
Java
// Java program to demonstrate forName() method
publicclassTest
{
publicstaticvoidmain(String[] args)
throwsClassNotFoundException
{
// returns the Class object for this class
Class myClass = Class.forName("Test");
ClassLoader loader = myClass.getClassLoader();
// forName method
// it returns the Class object for the class
// with the specified name using the given class loader
Class c = Class.forName("java.lang.String",true,loader);
System.out.print("Class represented by c : " + c.toString());
}
}
Output:
Class represented by c : class java.lang.String
T newInstance() : This method creates a new instance of the class represented by this Class object. The class is created as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.
Syntax :
public T newInstance() throws InstantiationException,IllegalAccessException
TypeParameters :
T - The class type whose instance is to be returned
Parameters :
NA
Returns :
a newly allocated instance of the class represented by this object.
Throws :
IllegalAccessException - if the class or its nullary constructor is not accessible.
InstantiationException - if this Class represents an abstract class, an interface,
an array class, a primitive type, or void
or if the class has no nullary constructor;
or if the instantiation fails for some other reason.
ExceptionInInitializerError - if the initialization provoked by this method fails.
SecurityException - If a security manager, s, is present
Java
// Java program to demonstrate newInstance() method
System.out.println("Class of obj : " + obj.getClass());
}
}
Output:
Class of obj : class Test
boolean isInstance(Object obj) : This method determines if the specified Object is assignment-compatible with the object represented by this Class. It is equivalent to instanceof operator in java.
Syntax :
public boolean isInstance(Object obj)
Parameters :
obj - the object to check
Returns :
true if obj is an instance of this class else return false
Java
// Java program to demonstrate isInstance() method
publicclassTest
{
publicstaticvoidmain(String[] args)
throwsClassNotFoundException
{
// returns the Class object for the class
// with the specified name
Class c = Class.forName("java.lang.String");
String s = "GeeksForGeeks";
inti = 10;
// checking for Class instance
// isInstance method
booleanb1 = c.isInstance(s);
booleanb2 = c.isInstance(i);
System.out.println("is s instance of String : " + b1);
System.out.println("is i instance of String : " + b1);
}
}
Output:
is s instance of String : true
is i instance of String : false
boolean isAssignableFrom(Class<?> cls) : This method determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface, of the class or interface represented by the specified Class parameter.
Syntax :
public boolean isAssignableFrom(Class<?> cls)
Parameters :
cls - the Class object to be checked
Returns :
true if objects of the type cls can be assigned to objects of this class
Throws:
NullPointerException - if the specified Class parameter is null.
Java
// Java program to demonstrate isAssignableFrom() method
is int primitive : true
is class Test primitive : false
boolean isArray() : This method determines if the specified Class object represents an array class.
Syntax :
public boolean isArray()
Parameters :
NA
Returns :
return true if and only if this class represents an array type else return false
Java
// Java program to demonstrate isArray method
publicclassTest
{
publicstaticvoidmain(String[] args)
{
inta[] = newint[2];
// returns the Class object for array class
Class c1 = a.getClass();
// returns the Class object for Test class
Class c2 = Test.class;
// checking for array type
// isArray method on c1
booleanb1 = c1.isArray();
// is Array method on c2
booleanb2 = c2.isArray();
System.out.println("is "+c1.toString()+" an array : " + b1);
System.out.println("is "+c2.toString()+" an array : " + b2);
}
}
Output:
is class [I an array : true
is class Test an array : false
boolean isAnonymousClass() : This method returns true if and only if the this class is an anonymous class. A anonymous class is a like a local classes except that they do not have a name.
Syntax :
public boolean isAnonymousClass()
Parameters :
NA
Returns :
true if and only if this class is an anonymous class.
false,otherwise.
boolean isLocalClass() : This method returns true if and only if the this class is a local class. A local class is a class that is declared locally within a block of Java code, rather than as a member of a class.
Syntax :
public boolean isLocalClass()
Parameters :
NA
Returns :
true if and only if this class is a local class.
false,otherwise.
boolean isMemberClass() : This method returns true if and only if the this class is a Member class.A member class is a class that is declared as a non-static member of a containing class.
Syntax :
public boolean isMemberClass()
Parameters :
NA
Returns :
true if and only if this class is a Member class.
false,otherwise.
boolean isEnum() : This method returns true if and only if this class was declared as an enum in the source code.
Syntax :
public boolean isEnum()
Parameters :
NA
Returns :
true if this class was declared as an enum in the source code.
false,otherwise.
Java
// Java program to demonstrate isEnum() method
enumColor
{
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 class
Class c2 = Test.class;
// checking for Enum class
// isEnum method
booleanb1 = c1.isEnum();
booleanb2 = c2.isEnum();
System.out.println("is "+c1.toString()+" an Enum class: " + b1);
System.out.println("is "+c2.toString()+" an Enum class: " + b2);
}
}
Output:
is class Color an Enum class : true
is class Test an Enum class : false
boolean isAnnotation() : This method determines if this Class object represents an annotation type. Note that if this method returns true, isInterface() method will also return true, as all annotation types are also interfaces.
Syntax :
public boolean isAnnotation()
Parameters :
NA
Returns :
return true if and only if this class represents an annotation type else return false
Java
// Java program to demonstrate isAnnotation() method
// declaring an Annotation Type
@interfaceA
{
// Annotation element definitions
}
publicclassTest
{
publicstaticvoidmain(String[] args)
throwsClassNotFoundException
{
// returns the Class object associated with A annotation
Class c1 = A.class;
// returns the Class object associated with Test class
Class c2 = Test.class;
// checking for annotation type
// isAnnotation method
booleanb1 = c1.isAnnotation();
booleanb2 = c2.isAnnotation();
System.out.println("is "+c1.toString()+" an annotation : " + b1);
System.out.println("is "+c2.toString()+" an annotation : " + b2);
}
}
Output:
is interface A an annotation : true
is class Test an annotation : false
String getName() : This method returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String.
Syntax :
public String getName()
Parameters :
NA
Returns :
returns the name of the name of the entity
represented by this object.
Java
// Java program to demonstrate getName() method
publicclassTest
{
publicstaticvoidmain(String[] args)
{
// returns the Class object associated with Test class
Class c = Test.class;
System.out.print("Class Name associated with c : ");
// returns the name of the class
// getName method
System.out.println(c.getName());
}
}
Output:
Class Name associated with c : Test
String getSimpleName() : This method returns the name of the underlying class as given in the source code. It returns an empty string if the underlying class is anonymous class. The simple name of an array is the simple name of the component type with “[]” appended. In particular the simple name of an array whose component type is anonymous is “[]”.
Syntax :
public String getSimpleName()
Parameters :
NA
Returns :
the simple name of the underlying class
Java
// Java program to demonstrate getSimpleName() method
publicclassTest
{
publicstaticvoidmain(String[] args)
throwsClassNotFoundException
{
// returns the Class object for the class
// with the specified name
Class c1 = Class.forName("java.lang.String");
System.out.print("Class Name associated with c : ");
// returns the name of the class
// getName method
System.out.println(c1.getName());
System.out.print("Simple className associated with c : ");
// returns the simple name of the class
// getSimpleName method
System.out.println(c1.getSimpleName());
}
}
Output:
Class Name associated with c : java.lang.String
Simple class Name associated with c : String
ClassLoader getClassLoader() : This method returns the class loader for this class. If the class loader is bootstrap classloader then this method returned null, as bootstrap classloader is implemented in native languages like C, C++. If this object represents a primitive type or void,then also null is returned.
Syntax :
public ClassLoader getClassLoader()
Parameters :
NA
Returns :
the class loader that loaded the class or interface represented by this object
represented by this object.
Throws :
SecurityException - If a security manager and its checkPermission method
denies access to the class loader for the class.
Java
// Java program to demonstrate getClassLoader() method
publicclassTest
{
publicstaticvoidmain(String[] args)
throwsClassNotFoundException
{
// returns the Class object for this class
Class myClass = Class.forName("Test");
// returns the Class object for the class
// with the specified name
Class c1 = Class.forName("java.lang.String");
// returns the Class object for primitive int
Class c2 = int.class;
System.out.print("Test classloader : ");
// getting the class loader for Test class
// getClassLoader method on myClass
System.out.println(myClass.getClassLoader());
System.out.print("String classloader : ");
// getting the class loader for String class
// we will get null as String class is loaded
// by BootStrap class loader
// getClassLoader method on c1
System.out.println(c1.getClassLoader());
System.out.print("primitive intloader : ");
// getting the class loader for primitive int
// getClassLoader method on c2
System.out.println(c2.getClassLoader());
}
}
Output:
Test class loader : sun.misc.Launcher$AppClassLoader@73d16e93
String class loader : null
primitive int loader : null
TypeVariable<Class<T>>[ ] getTypeParameters() : This method returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration order
Syntax :
public TypeVariable<Class<T>>[] getTypeParameters()
Specified by:getTypeParameters in interface GenericDeclarationParameters :
NA
Returns :
an array of TypeVariable objects that represent the type variables declared
by this generic declaration represented by this object.
Throws :
GenericSignatureFormatError - if the generic signature of this generic declaration
does not conform to the format specified in JVM.
Java
// Java program to demonstrate getTypeParameters() method
importjava.lang.reflect.TypeVariable;
publicclassTest
{
publicstaticvoidmain(String[] args)
throwsClassNotFoundException
{
// returns the Class object for the class
// with the specified name
Class c = Class.forName("java.util.Set");
// getting array of TypeVariable for myClass object
// getTypeParameters method
TypeVariable[] tv = c.getTypeParameters();
System.out.println("TypeVariables in "+c.getName()+" class: ");
// iterating through all TypeVariables
for(TypeVariable typeVariable : tv)
{
System.out.println(typeVariable);
}
}
}
Output:
TypeVariables in java.util.Set class :
E
Class<? super T> getSuperclass() : This method returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class. If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned. If this object represents an array class then the Class object representing the Object class is returned.
Syntax :
public Class<? super T> getSuperclass()
Parameters :
NA
Returns :
the superclass of the class represented by this object
Java
// Java program to demonstrate getSuperclass() method
// base class
classA
{
// methods and fields
}
// derived class
classB extendsA
{
}
// Driver class
publicclassTest
{
publicstaticvoidmain(String[] args)
throwsClassNotFoundException
{
// returns the Class object associated with Test class
Class myClass = Test.class;
// returns the Class object for the class
// with the specified name
Class c1 = Class.forName("A");
Class c2 = Class.forName("B");
Class c3 = Class.forName("java.lang.Object");
// getSuperclass method returns the superclass of the class represented
// by this class object
System.out.print("Test superclass : ");
// getSuperclass method on myClass
System.out.println(myClass.getSuperclass());
System.out.print("A superclass : ");
// getSuperclass method on c1
System.out.println(c1.getSuperclass());
System.out.print("B superclass : ");
// getSuperclass method on c2
System.out.println(c2.getSuperclass());
System.out.print("Object superclass : ");
// getSuperclass method on c3
System.out.println(c3.getSuperclass());
}
}
Output:
Test superclass : class java.lang.Object
A superclass : class java.lang.Object
B superclass : class A
Object superclass : null
Type getGenericSuperclass() : This method returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class. If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned. If this object represents an array class then the Class object representing the Object class is returned.
Syntax :
public Type getGenericSuperclass()
Parameters :
NA
Returns :
the superclass of the class represented by this object
Throws:
GenericSignatureFormatError - if the generic class signature does not conform to the format
specified in JVM
TypeNotPresentException - if the generic superclass refers to a non-existent
type declaration MalformedParameterizedTypeException - if the generic
superclass refers to a parameterized type
that cannot be instantiated for any reason
Java
// Java program to demonstrate
// getGenericSuperclass() method
publicclassTest
{
publicstaticvoidmain(String[] args)
throwsClassNotFoundException
{
// returns the Class object associated with Test class
Class myClass = Test.class;
// returns the Class object for the class
// with the specified name
Class c1 = Class.forName("java.util.ArrayList");
Class c3 = Class.forName("java.lang.Object");
// getGenericSuperclass method returns the generic
Test superclass : class java.lang.Object
Set superclass : java.util.AbstractList<E>
Object superclass : null
Class<?>[] getInterfaces() : This method returns the interfaces implemented by the class or interface represented by this object. If this object represents a class or interface that implements no interfaces, the method returns an array of length 0. If this object represents a primitive type or void, the method returns an array of length 0.
Syntax :
public Class<?>[] getInterfaces()
Parameters :
NA
Returns :
an array of interfaces implemented by this class.
Java
// Java program to demonstrate getInterfaces() method
// base interface
interfaceA
{
// methods and constant declarations
}
// derived class
classB implementsA
{
// methods implementations that were declared in A
}
// Driver class
publicclassTest
{
publicstaticvoidmain(String[] args)
throwsClassNotFoundException
{
// returns the Class object for the class
// with the specified name
Class c1 = Class.forName("B");
Class c2 = Class.forName("java.lang.String");
// getInterface method on c1
// it returns the interfaces implemented by B class
Class c1Interfaces[] = c1.getInterfaces();
// getInterface method on c2
// returns the interfaces implemented by String class
Class c2Interfaces[] = c2.getInterfaces();
System.out.println("interfaces implemented by B class: ");
// iterating through B class interfaces
for(Class class1 : c1Interfaces)
{
System.out.println(class1);
}
System.out.println("interfaces implemented by String class: ");
// iterating through String class interfaces
for(Class class1 : c2Interfaces)
{
System.out.println(class1);
}
}
}
Output:
interfaces implemented by B class :
interface A
interfaces implemented by String class :
interface java.io.Serializable
interface java.lang.Comparable
interface java.lang.CharSequence
Type[] getGenericInterfaces() : This method returns the Types representing the interfaces directly implemented by the class or interface represented by this object. If this object represents a class or interface that implements no interfaces, the method returns an array of length 0. If this object represents a primitive type or void, the method returns an array of length 0.
Syntax :
public Type[] getGenericInterfaces()
Parameters :
NA
Returns :
an array of interfaces implemented by this class
Throws:
GenericSignatureFormatError - if the generic class signature does not conform to the format
specified in JVM
TypeNotPresentException - if the generic superinterfaces refers to
a non-existent type declaration MalformedParameterizedTypeException - if the
generic superinterfaces refers to a parameterized type
that cannot be instantiated for any reason
Java
// Java program to demonstrate getGenericInterfaces() method
importjava.lang.reflect.Type;
publicclassTest
{
publicstaticvoidmain(String[] args)
throwsClassNotFoundException
{
// returns the Class object for the class
// with the specified name
Class c1 = Class.forName("java.util.Set");
// getGenericInterfaces() on c1
// it returns the interfaces implemented by Set interface
Type c1GenericInterfaces[] = c1.getGenericInterfaces();
System.out.println("interfaces implemented by Set interface: ");
// iterating through Set class interfaces
for(Type type : c1GenericInterfaces)
{
System.out.println(type);
}
}
}
Output:
interfaces implemented by Set interface :
java.util.Collection<E>
Package getPackage() : This method returns the package for this class. The classloader subsystem in JVM Architecture used this method to find the package of a class or interface.
Syntax :
public Package getPackage()
Parameters :
NA
Returns :
the package of the class,
or null if no package information is available
from the archive or codebase.
Java
// Java program to demonstrate getPackage() method
package java.lang, Java Platform API Specification, version 1.8
package java.util, Java Platform API Specification, version 1.8
Field[] getFields() : This method returns an array of Field objects reflecting all the accessible public fields of the class(and of all its superclasses) or interface(and of all its superclasses) represented by this Class object.
Syntax :
public Field[] getFields() throws SecurityException
Parameters :
NA
Returns :
the array of Field objects representing the public fields
and array of length 0 if the class or interface has no accessible public fields
or if this Class object represents a primitive type or void.
Throws :
SecurityException - If a security manager, s, is present.
Java
// Java program to demonstrate getFields() method
importjava.lang.reflect.Field;
publicclassTest
{
publicstaticvoidmain(String[] args)
throwsSecurityException,ClassNotFoundException
{
// returns the Class object for the class
// with the specified name
Class c1 = Class.forName("java.lang.Integer");
// getFields method on c1
// it array of fields of Integer class
Field F[] = c1.getFields();
System.out.println("Below are the fields of Integer class: ");
// iterating through all fields of String class
for(Field field : F)
{
System.out.println(field);
}
}
}
Output :
Below are the fields of Integer class :
public static final int java.lang.Integer.MIN_VALUE
public static final int java.lang.Integer.MAX_VALUE
public static final java.lang.Class java.lang.Integer.TYPE
public static final int java.lang.Integer.SIZE
public static final int java.lang.Integer.BYTES
Class<?>[ ] getClasses() : This method returns an array containing Class objects representing all the public classes and interfaces that are members of the class represented by this Class object. The array contains public class and interface members inherited from superclasses and public class and interface members declared by the class. This method returns an array of length 0 if this Class object has no public member classes or interfaces. This method also returns an array of length 0 if this Class object represents a primitive type, an array class, or void.
Syntax :
Class<?>[ ] getClasses()
Parameters :
NA
Returns :
the array of Class objects representing the public members of this class
Throws :
SecurityException - If a security manager, s, is present.
Java
// Java program to demonstrate getClasses() method
publicclassTest
{
// base interface
publicinterfaceA
{
// methods and constant declarations
}
// derived class
publicclassB implementsA
{
// methods implementations that were declared in A
}
publicstaticvoidmain(String[] args)
throwsClassNotFoundException
{
// returns the Class object associated with Test class
Class c1 = Test.class;
// getClasses method on c1
// it returns the array of Class objects containing the all
// public classes and interfaces represented by Test class
Class[] c1Classes = c1.getClasses();
System.out.println("publicmembers of Test class: ");
// iterating through all public members of Test class
for(Class class1 : c1Classes)
{
System.out.println(class1);
}
}
}
Output:
public members of Test class :
interface Test$A
class Test$B
Method[] getMethods() : This method returns an array of Method objects reflecting all the accessible public methods of the class or interface and those inherited from superclasses and super interfaces represented by this Class object.
Syntax :
public Method[] getMethods() throws SecurityException
Parameters :
NA
Returns :
the array of Method objects representing the public methods
and array of length 0 if the class or interface has no accessible public method
or if this Class object represents a primitive type or void.
Throws :
SecurityException - If a security manager, s, is present.
Java
// Java program to demonstrate getMethods() method
importjava.lang.reflect.Method;
publicclassTest
{
publicstaticvoidmain(String[] args)
throwsSecurityException,ClassNotFoundException
{
// returns the Class object for the class
// with the specified name
Class c1 = Class.forName("java.lang.Object");
// getMethods method on c1
// it returns array of methods of Object class
Method M[] = c1.getMethods();
System.out.println("Below are the methods of Object class: ");
// iterating through all methods of Object class
for(Method method : M)
{
System.out.println(method);
}
}
}
Output:
Below are the methods of Object class :
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
Constructor<?>[] getConstructors() : This method returns an array of Constructor objects reflecting all the public constructors of the class represented by this Class object.
Syntax :
public Constructor<?>[] getConstructors() throws SecurityException
Parameters :
NA
Returns :
the array of Constructor objects representing the public constructors of this class
and array of length 0 if the class or interface has no accessible public constructor
or if this Class object represents a primitive type or void.
Throws :
SecurityException - If a security manager, s, is present.
Java
// Java program to demonstrate getConstructors() method
importjava.lang.reflect.Constructor;
publicclassTest
{
publicstaticvoidmain(String[] args)
throwsSecurityException,ClassNotFoundException
{
// returns the Class object for the class
// with the specified name
Class c1 = Class.forName("java.lang.Boolean");
// getConstructor method on c1
// it returns an array of constructors of Boolean class
Constructor C[] = c1.getConstructors();
System.out.println("Below are the constructors of Boolean class:");
// iterating through all constructors
for(Constructor constructor : C)
{
System.out.println(constructor);
}
}
}
Output:
Below are the constructors of Boolean class :
public java.lang.Boolean(boolean)
public java.lang.Boolean(java.lang.String)
Field getField(String fieldName) : This method returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.
Syntax :
public Field getField(String fieldName) throws NoSuchFieldException,SecurityException
Parameters :
fieldName - the field name
Returns :
the Field object of this class specified by name
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
// Java program to demonstrate getField() method
importjava.lang.reflect.Field;
publicclassTest
{
publicstaticvoidmain(String[] args)
throwsSecurityException,ClassNotFoundException,
NoSuchFieldException
{
// returns the Class object for the class
// with the specified name
Class c1 = Class.forName("java.lang.Integer");
// getField method on c1
// it checks a public field in Integer class with specified parameter
Field f = c1.getField("MIN_VALUE");
System.out.println("publicfield in Integer classwith MIN_VALUE name :");
System.out.println(f);
}
}
Output:
public field in Integer class with MIN_VALUE name :
public static final int java.lang.Integer.MIN_VALUE
Method getMethod(String methodName,Class… parameterTypes) : This method returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.
Syntax :
public Method getMethod(String methodName,Class... parameterTypes) throws
NoSuchFieldException,SecurityException
Parameters :
methodName - the method name
parameterTypes - the list of parameters
Returns :
the method object of this class specified by name
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
// Java program to demonstrate getMethod() method
importjava.lang.reflect.Method;
publicclassTest
{
publicstaticvoidmain(String[] args)
throwsSecurityException,ClassNotFoundException,
NoSuchMethodException
{
// returns the Class object for the class
// with the specified name
Class c1 = Class.forName("java.lang.Integer");
Class c2 = Class.forName("java.lang.String");
// getMethod method on c1
// it checks for a public Method in Integer class
Method m = c1.getMethod("parseInt",c2);
System.out.println("method in Integer classspecified by parseInt : ");
System.out.println(m);
}
}
Output:
public method in Integer class specified by parseInt :
public static int java.lang.Integer.parseInt(java.lang.String)
throws java.lang.NumberFormatException
Constructor<?> getConstructor(Class<?>… parameterTypes) : This method returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.The parameterTypes parameter is an array of Class objects that identify the constructor’s formal parameter types, in declared order.
Syntax :
public Constructor<?> getConstructor(Class<?>... parameterTypes)
throws NoSuchMethodException,SecurityException
Parameters :
parameterTypes - the list of parameters
Returns :
the Constructor object of the public constructor that matches the specified parameterTypes
Throws :
NoSuchMethodException - if a Constructor with the specified parameterTypes is not found.
SecurityException - If a security manager, s, is present.
Java
// Java program to demonstrate
// getConstructor() Constructor
importjava.lang.reflect.Constructor;
publicclassTest
{
publicstaticvoidmain(String[] args)
throwsSecurityException,ClassNotFoundException,
NoSuchMethodException
{
// returns the Class object for the class
// with the specified name
Class c1 = Class.forName("java.lang.Integer");
Class c2 = Class.forName("java.lang.String");
// getConstructor method on c1
// it checks a public Constructor in Integer class
// with specified parameterTypes
Constructor c = c1.getConstructor(c2);
System.out.println("Constructor in Integer class& String parameterType:");
System.out.println(c);
}
}
Output:
public Constructor in Integer class with String parameterType :
public java.lang.Integer(java.lang.String) throws java.lang.NumberFormatException
T cast(Object obj) : This method is used to casts an object to the class or interface represented by this Class object.
Syntax :
public T cast(Object obj)
TypeParameters :
T - The class type whose object is to be cast
Parameters :
obj - the object to be cast
Returns :
the object after casting, or null if obj is null
Throws :
ClassCastException - if the object is not null and is not assignable to the type T.
Java
// Java program to demonstrate cast() method
classA
{
// methods and fields
}
classB extendsA
{
// methods and fields
}
// Driver Class
publicclassTest
{
publicstaticvoidmain(String[] args)
{
A a = newA();
System.out.println(a.getClass());
B b = newB();
// casting b to a
// cast method
a = A.class.cast(b);
System.out.println(a.getClass());
}
}
Output
class A
class B
Output:
class A
class B
<U> Class<? extends U> asSubclass(Class<U> clazz) : This method is used to cast this Class object to represent a subclass of the class represented by the specified class object.It always returns a reference to this class object.
Syntax :
public <U> Class<? extends U> asSubclass(Class<U> class)
TypeParameters :
U - The superclass type whose object is to be cast
Parameters :
clazz - the superclass object to be cast
Returns :
this Class object, cast to represent a subclass of the specified class object.
Throws :
ClassCastException - if this Class object does not represent a
subclass of the specified class
(here "subclass" includes the class itself).
Java
// Java program to demonstrate asSubclass() method
classA
{
// methods and fields
}
classB extendsA
{
// methods and fields
}
// Driver Class
publicclassTest
{
publicstaticvoidmain(String[] args)
{
A a = newA();
// returns the Class object for super class(A)
Class superClass = a.getClass();
B b = newB();
// returns the Class object for subclass(B)
Class subClass = b.getClass();
// asSubclass method
// it represent a subclass of the specified class object
Class cast = subClass.asSubclass(superClass);
System.out.println(cast);
}
}
Output
class B
Output:
class B
Feeling lost in the vast world of Backend Development? It's time for a change! Join our Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule. What We Offer:
Comprehensive Course
Expert Guidance for Efficient Learning
Hands-on Experience with Real-world Projects
Proven Track Record with 100,000+ Successful Geeks
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Please go through our recently updated Improvement Guidelines before submitting any improvements.
This article is being improved by another user right now. You can suggest the changes for now and it will be under the article's discussion tab.
You will be notified via email once the article is available for improvement.
Thank you for your valuable feedback!
Please go through our recently updated Improvement Guidelines before submitting any improvements.
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.