Download java lang Class Class in Formats
QR Code for this Page
java lang Class Class

java lang Class Class

java.lang.Class Class

Class Class in Java

Class represents classes and interfaces in a running Java application. An enum is a kind of class and an annotation is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.

Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.

java.lang.Class class in Java

Every time JVM creates an object , it also creates a java.lang.Class object that describes the type of the object . All instances of the same class share the same Class object and you can obtain the Class object by calling the getClass() method of the object . This method is inherited from java.lang.Object class .

What is the use of class java.lang.Class in Java ?

java.lang.Class is one of the most important class in Java . It is very useful , it provides several utility methods getClass(), forName() which is used to find and load a class , you might have used to load Oracle , MySQL and MSSQL drivers class . It also provides methods like Class.newInstance() which is the backbone of reflection and allow you to create an instance of a class without using new() operator . This class has no public constructor and its instance is created by JVM when a class is loaded . Another use of java.lang.Class is while implementing equals() method to check whether two objects are of the same type or not . It is a final class , so we cannot extend it .

We need java.lang.Class.forName() and java.lang.Class.newInstance() because many times it happens that we don't know the name of the class to instantiate while writing code , we may get it from config files , database , network or from any Java application . This is the reflective way of creating an object which is one of the most powerful feature of Java and which makes way for many frameworks e.g. Spring , Struts which uses Java reflection .

What does Class <?> Mean in Java ?

Class is a parameterizable class, hence you can use the syntax Class<T> where T is a type. By writing Class<?> , you're declaring a Class object which can be of any type ( ? is a wildcard). The Class type is a type that contains meta-information about a class .

How to create an object without using new operator in Java ?

By using the method java.lang.Class.newInstance() , which is the backbone of reflection and allow you to create an instance of a class without using new() operator . First you have to create Class object with the help of java.lang.Class.forName() method . The java.lang.Class.forName() actually loads the Class in Java but doesn't create any Object. To Create an Object of the Class, you have to use the newInstance method of the Class class.

Can you create an object without using new operator in Java ?

Yes, We can create an object without using new operator. There are some other ways to create objects other than using new operator. But almost all object creation in java is done through new operator only.

Example to create an object without using new operator

Class c = Class.forName("java.lang.String");
String object = (String) c.newInstance();

How many ways to create an object without using new operator in Java ?

We can create an object without using new operator. There are some other ways to create objects other than using new operator.

  1. Using newInstance() Method or Dynamic class Loading (Reflection)

    Have you ever tried to connect to a Database using the JDBC driver in Java ? you must have seen java.lang.Class.forName(). We can also use it to create the Object of a Class. Class.forName actually loads the Class in Java but doesn't create any Object. To Create an Object of the Class, you have to use the newInstance Method of the Class class.

    Class c = Class.forName("java.lang.String");
    String object = (String) c.newInstance();

  2. Using clone() method

    We can also use Clone() Method to create a copy of an existing Object . A class needs to implement Cloneable Interface otherwise it will throw CloneNotSupportedException .

    java.lang.String my_string = new String("java.lang.Class Example");
    String clone_object = my_string.clone();

  3. Using Object Deserialization

    Object deserialization can also be used to create an Object . It produces the opposite of serializing an Object .

    ObjectInputStream inStream = new ObjectInputStream(anInputStream );
    MyClass object = (MyClass) inStream.readObject();

  4. Creating string and array objects

    String s = "string object";
    int [ ] a = {1, 2, 3, 4};

What are the java.lang.Class class methods in Java ?

The java.lang.Object provides a number of methods that are common to all objects . The toString() is the most common such method . Since the default toString() method only produces the name of the class . java.lang.Object Class methods helps to perform the various operations like clone objects , compare objects , get the class name of the object . Following are the List of java.lang.Object Class Methods or functions .

Returns the Java language modifiers for this class or interface, encoded in an integer.
Modifier and Type Method Description
<U> Class<? extends U> java.lang.Class.asSubclass(Class<U> clazz) Casts this Class object to represent a subclass of the class represented by the specified class object.
T java.lang.Class.cast(Object obj) Casts an object to the class or interface represented by this Class object.
boolean java.lang.Class.desiredAssertionStatus() Returns the assertion status that would be assigned to this class if it were to be initialized at the time this method is invoked.
static Class<?> java.lang.Class.forName(String className) Returns the Class object associated with the class or interface with the given string name.
static Class<?> java.lang.Class.forName(String name, boolean initialize, ClassLoader loader) Returns the Class object associated with the class or interface with the given string name, using the given class loader.
AnnotatedType[] java.lang.Class.getAnnotatedInterfaces() Returns an array of AnnotatedType objects that represent the use of types to specify superinterfaces of the entity represented by this Class object.
AnnotatedType java.lang.Class.getAnnotatedSuperclass() Returns an AnnotatedType object that represents the use of a type to specify the superclass of the entity represented by this Class object.
<A extends Annotation>
A
java.lang.Class.getAnnotation(Class<A> annotationClass) Returns this element's annotation for the specified type if such an annotation is present, else null.
Annotation[] java.lang.Class.getAnnotations() Returns annotations that are present on this element.
Annotation>
A[]
java.lang.Class.getAnnotationsByType(Class<A> annotationClass) Returns annotations that are associated with this element.
String java.lang.Class.getCanonicalName() Returns the canonical name of the underlying class as defined by the Java Language Specification.
Class<?>[] java.lang.Class.getClasses() Returns an array containing Class objects representing all the public classes and interfaces that are members of the class represented by this Class object.
ClassLoader java.lang.Class.getClassLoader() Returns the class loader for the class.
Class<?> java.lang.Class.getComponentType() Returns the Class representing the component type of an array.
Constructor<T> java.lang.Class.getConstructor(Class<?>... parameterTypes) Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.
Constructor<?>[] java.lang.Class.getConstructors() Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.
<A extends Annotation>
A
java.lang.Class.getDeclaredAnnotation(Class<A> annotationClass) Returns this element's annotation for the specified type if such an annotation is directly present, else null.
Annotation[] java.lang.Class.getDeclaredAnnotations() Returns annotations that are directly present on this element.
<A extends Annotation>
A[]
java.lang.Class.getDeclaredAnnotationsByType (Class<A> annotationClass) Returns this element's annotation(s) for the specified type if such annotations are either directly present or indirectly present.
Class<?>[] java.lang.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.
Constructor<T> java.lang.Class.getDeclaredConstructor(Class<?>... parameterTypes) Returns a Constructor object that reflects the specified constructor of the class or interface represented by this Class object.
Constructor<?>[] java.lang.Class.getDeclaredConstructors() Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object.
Field java.lang.Class.getDeclaredField(String name) Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.
Field[] java.lang.Class.getDeclaredFields() Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.
Method java.lang.Class.getDeclaredMethod(String name, Class<?>... parameterTypes) Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.
Method[] java.lang.Class.getDeclaredMethods() Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package)access, and private methods, but excluding inherited methods.
Class<?> java.lang.Class.getDeclaringClass() If the class or interface represented by this Class object is a member of another class, returns the Class object representing the class in which it was declared.
Class<?> java.lang.Class.getEnclosingClass() Returns the immediately enclosing class of the underlying class.
Constructor<?> java.lang.Class.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.
Method java.lang.Class.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.
T[] java.lang.Class.getEnumConstants() Returns the elements of this enum class or null if this Class object does not represent an enum type.
Field java.lang.Class.getField(String name) Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.
Field[] java.lang.Class.getFields() Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.
Type[] java.lang.Class.getGenericInterfaces() Returns the Types representing the interfaces directly implemented by the class or interface represented by this object.
Type java.lang.Class.getGenericSuperclass() Returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class.
Class<?>[] java.lang.Class.getInterfaces() Determines the interfaces implemented by the class or interface represented by this object.
Method java.lang.Class.getMethod(String name, Class<?> ... parameterTypes) Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.
Method[] java.lang.Class.getMethods() Returns an array containing Method objects reflecting all the public methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.
int java.lang.Class.getModifiers()
String java.lang.Class.getName() Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String.
Package java.lang.Class.getPackage() Gets the package for this class.
ProtectionDomain java.lang.Class.getProtectionDomain() Returns the ProtectionDomain of this class.
URL java.lang.Class.getResource(String name) Finds a resource with a given name.
InputStream java.lang.Class.getResourceAsStream(String name) Finds a resource with a given name.
Object[] java.lang.Class.getSigners() Gets the signers of this class.
String java.lang.Class.getSimpleName() Returns the simple name of the underlying class as given in the source code.
Class<? super T> java.lang.Class.getSuperclass() Returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class.
String java.lang.Class.getTypeName() Return an informative string for the name of this type.
TypeVariable<Class<T>>[] java.lang.Class.getTypeParameters() Returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration order.
boolean java.lang.Class.isAnnotation() Returns true if this Class object represents an annotation type.
boolean java.lang.Class.isAnnotationPresent(Class<? extends Annotation> annotationClass) Returns true if an annotation for the specified type is present on this element, else false.
boolean java.lang.Class.isAnonymousClass() Returns true if and only if the underlying class is an anonymous class.
boolean java.lang.Class.isArray() Determines if this Class object represents an array class.
boolean java.lang.Class.isAssignableFrom(Class<?> cls) 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.
boolean java.lang.Class.isEnum() Returns true if and only if this class was declared as an enum in the source code.
boolean java.lang.Class.isInstance(Object obj) Determines if the specified Object is assignment-compatible with the object represented by this Class.
boolean java.lang.Class.isInterface() Determines if the specified Class object represents an interface type.
boolean java.lang.Class.isLocalClass() Returns true if and only if the underlying class is a local class.
boolean java.lang.Class.isMemberClass() Returns true if and only if the underlying class is a member class.
boolean java.lang.Class.isPrimitive() Determines if the specified Class object represents a primitive type.
boolean java.lang.Class.isSynthetic() Returns true if this class is a synthetic class; returns false otherwise.
T java.lang.Class.newInstance() Creates a new instance of the class represented by this Class object.
String java.lang.Class.toGenericString() Returns a string describing this Class, including information about modifiers and type parameters.
String java.lang.Class.toString() Converts the object to a string.

In this tutorial you can learn how to use Class class.

java.lang.Class Class Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*  This class is supporting class for Examples of Class class
    Save with file name Student.java  */
  
//Student IS THE CLASS NAME
public class Student
{
  //FIELDS OF THE Student CLASS
  public int sid;
  public String sname;
  public String scollege;
  
  //CONSTRUCTORS OF THE Student CLASS
  public Student(){}
  public Student(int sid, String sname, String scollege)
  {
    this.sid = sid;
    this.sname = sname;
    this.scollege = scollege;
  }
  //SETTER METHODS OF THE Student CLASS
  public void setStudentID(int sid)
  {
    this.sid = sid;
  }
  public void setStudentName(String sname)
  {
    this.sname = sname;
  }
  public void setStudentCollege(String scollege)
  {
    this.scollege = scollege;
  }
  //GETTER METHODS OF THE Student CLASS
  public int getStudentID()
  {
    return this.sid;
  }
  public String getStudentName()
  {
    return this.sname;
  }
  public String getStudentCollege(String scollege)
  {
    return this.scollege;
  }
  public String toString()
  {
    return (this.sid+" "+this.sname+" "+this.scollege);
  }
}

How to get class name, package and canonical name of a class using Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*  How to get class name, package and canonical name
    of a class using Java Example
    Save with file name ClassExample1.java  */
  
import java.lang.reflect.*;
  
public class ClassExample1
{
  public static void main(String args[])
  {
    //Student CLASS DECLARATION
    Student s;
    //CREATE INSTANCE FOR Student CLASS
    s = new Student(1, "Huda", "http://www.hudatutorials.com");
    //Class CLASS DECLARATION
    Class c;
    //CREATE INSTANCE FOR Class CLASS
    //getClass() METHOD IS Object CLASS METHOD
    //IT IS CALLED FROM Student CLASS
    //BECAUSE Object CLASS IS SUPER (PARENT) CLASS
    c = s.getClass();
    //RETURNS THE CLASS NAME
    System.out.println("Class Name : " + c.getName());
    //RETURNS THE CLASS SIMPLE NAME
    System.out.println("Class Simple Name : " + c.getSimpleName());
    //RETURNS THE CLASS CANONICAL NAME
    System.out.println("Class Canonical Name : " + c.getCanonicalName());
    //RETURNS THE CLASS PACKAGE
    //RETURNS null IF NO PACKAGE DECLARED
    System.out.println("Package of the Class : " + c.getPackage());
  }
}

How to get class Fields, Methods, Constructors using Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*  How to get class Fields, Methods,
    Constructors using Java Example
    Save with file name ClassExample2.java  */
  
import java.lang.reflect.*;
  
public class ClassExample2
{
  public static void main(String args[])
  {
    //Student CLASS DECLARATION
    Student s;
    //CREATE INSTANCE FOR Student CLASS
    s = new Student(1, "Huda", "http://www.hudatutorials.com");
    //Class CLASS DECLARATION
    Class c;
    //CREATE INSTANCE FOR Class CLASS
    //getClass() METHOD IS Object CLASS METHOD
    //IT IS CALLED FROM Student CLASS
    //BECAUSE Object CLASS IS SUPER (PARENT) CLASS
    c = s.getClass();
    //GETTING THE FIELDS OF CLASS
    Field fields[] = c.getFields();
    System.out.println("FIELDS");
    for(int i=0;i<fields.length;i++)
    {
      System.out.println("Field "+ (i+1) + " => " + fields[i]);
    }
  
    System.out.println();
    //GETTING THE CONSTRUCTORS OF CLASS
    Constructor con[] = c.getConstructors();
    System.out.println("CONSTRUCTORS");
    for(int i=0;i<con.length;i++)
    {
      System.out.println("Constructor "+ (i+1) + " => " + con[i]);
    }
    System.out.println();
    //GETTING THE METHODS OF CLASS
    Method m[] = c.getMethods();
    System.out.println("METHODS");
    for(int i=0;i<m.length;i++)
    {
      System.out.println();
      System.out.format("Method %3d  => " + m[i], (i+1));
    }
  }
}
Download java lang Class Class in Formats