Signup/Sign In

Java Class class

In our previous topic, we discussed about how to load a class at runtime using various ways. Here we will see how to get metadata of that class, its methods and fields.

Class is a final class in java.lang package which extends Object class. Instance of this class represents classes and interfaces in a running Java application. It is used to analyze and change dynamic behaviour of a class at runtime.

Methods of java.lang.Class class

This class defines several methods using which we can get information about methods, constructors, modifiers and members of a class at runtime.

forName()

This method takes fully qualified name of classes or interface as its argument and returns instance of the class assocaited with it.

Syntax

static Class< ?> forName(String className)

Example: Fetch Class Metadata

To get metadata of a class, first we need to load the class using class.forName() method and then use Class methods. In this example, we used getName() method to get name of the class and getDeclaredFields() to get all the fields of the class. See the below example.

  
package myjavaproject;

import java.util.Arrays;

// Employee Class
class Employee{

  // Fields 
  int empId;
  String name;
  
  // Constructor
  Employee(int empId, String name){
    this.empId = empId;
    this.name = name;
  }
  
  // Method
  void showInfo() {
    System.out.println("Employee Id: "+empId);
    System.out.println("Employee Name: "+name);
  }
}

class Demo{
  public static void main(String[] args) throws ClassNotFoundException {
    
    // Employee class
    Class name = Class.forName("myjavaproject.Employee");
    // Get class Name
    System.out.println(name.getName());
    // Get Package
    System.out.println(name.getPackageName());
    System.out.println(name.getTypeName());
    Arrays.stream(name.getDeclaredConstructors()).forEach(System.out::println);
    Arrays.stream(name.getDeclaredFields()).forEach(System.out::println);
    Arrays.stream(name.getDeclaredMethods()).forEach(System.out::println);
  }
} 
  

myjavaproject.Employee myjavaproject myjavaproject.Employee myjavaproject.Employee(int,java.lang.String) int myjavaproject.Employee.empId java.lang.String myjavaproject.Employee.name void myjavaproject.Employee.showInfo()

Example: Get Field Metadata

To deal with class fields, Java provides a Field class which is located into java.lang.reflect package. This class contains methods that helps to get metadata of a field. In this example, you can see that we used class.forName to load the class and then Field class to get metadata of the class.

  
package myjavaproject;

import java.lang.reflect.Field;

// Employee Class
class Employee{

  // Fields 
  int empId;
  String name;
  
  // Constructor
  Employee(int empId, String name){
    this.empId = empId;
    this.name = name;
  }
  
  // Method
  void showInfo() {
    System.out.println("Employee Id: "+empId);
    System.out.println("Employee Name: "+name);
  }
}

class Demo{
  public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException {
    
    // Employee class
    Class name = Class.forName("myjavaproject.Employee");
    // Get Fields metadata
    Field[] field = name.getDeclaredFields();
    for(Field f: field) {
      System.out.print(f.getType()+" ");
      System.out.println(f.getName());
      System.out.println(f.getModifiers());     
    }   
  }
}
  

int empId 0 class java.lang.String name 0

Example: Get Method Metadata

To deal with class methods, Java provides a Method class which is located into java.lang.reflect package. This class contains methods that helps to get metadata of a method. In this example, you can see that we used class.forName to load the class and then Method class to get metadata of the method.

  
import java.lang.reflect.Method;

// Employee Class
class Employee{

  // Fields 
  int empId;
  String name;
  
  // Constructor
  Employee(int empId, String name){
    this.empId = empId;
    this.name = name;
  }
  
  // Method
  void showInfo() {
    System.out.println("Employee Id: "+empId);
    System.out.println("Employee Name: "+name);
  }
}

class Demo{
  public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException {
    
    // Employee class
    Class name = Class.forName("myjavaproject.Employee");
    // Get method metadata
    Method[] method = name.getDeclaredMethods();
    for(Method m: method) {
      System.out.println(m);
      System.out.println(m.getDefaultValue());
      System.out.println(m.getModifiers());
      System.out.println(m.getName());
      System.out.println(m.getParameterCount());
      System.out.println(m.getReturnType());
    }   
  }
}
  

void myjavaproject.Employee.showInfo() null 0 showInfo 0 void

Example: Get Constructor Metadata

A class may have several constructors including parameterized and non parameterized as well. Java reflection provides the Constructor class that consists of methods and can be used to get metadata of constructor. In this example, we used constructor class and its methods to get metadata of constructors. See the example below.

  
  package myjavaproject;

import java.lang.reflect.Constructor;
import java.lang.reflect.Parameter;

// Employee Class
class Employee{

  // Fields 
  int empId;
  String name;
  
  // Constructor
  Employee(int empId, String name){
    this.empId = empId;
    this.name = name;
  }
  
  // Method
  void showInfo() {
    System.out.println("Employee Id: "+empId);
    System.out.println("Employee Name: "+name);
  }
}

class Demo{
  public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException {
    
    // Employee class
    Class name = Class.forName("myjavaproject.Employee");
    // Get method metadata
    Constructor[] constructor = name.getDeclaredConstructors();
    for(Constructor c: constructor) {
      System.out.println(c);
      System.out.println(c.getModifiers());
      System.out.println(c.getName());
      System.out.println(c.getParameterCount());
      System.out.println(c.getDeclaringClass());
      Parameter[] parameters = c.getParameters();
      for(Parameter p : parameters) {
        System.out.println(p);
      }
      
      Class[] pt = c.getParameterTypes();
      for(Class s : pt) {
        System.out.println(s);
      }
    }   
  }
}
  

myjavaproject.Employee(int,java.lang.String) 0 myjavaproject.Employee 2 class myjavaproject.Employee int arg0 java.lang.String arg1 int class java.lang.Strings

getConstructors() and getDeclaredConstructors()

getConstructors() method returns array of Constructors object that represent all the public constructors of the invoking object. Remember, this method only returns public constructors. If you want to see all the declared constructors of a class then use getDeclaredConstructors(). Following is the general syntax of both,

Constructor< ?>[] getConstructors();
Constructor< ?>[] getDeclaredConstructors();

Example: getConstructors() and getDeclaredConstructors() method

Both the methods are used to get class constructors but the getConstructors() returns only public constructors whereas getDeclaredConstructors() returns all the available constructors.

import java.lang.reflect.*;
class Student
{
  public Student(){}
  public Student(String name){}
}

class Test
{
  public static void main(String args[])
  {
    try
    {
      Class c = Class.forName("Student");
      Constructor< Student>[] ct = c.getConstructors();
      for(int i=0; i< ct.length; i++)
      { System.out.println(ct[i]); }
      Constructor< Student>[]cdt = c.getDeclaredConstructors();
      for(int i=0;i< cdt.length;i++)
      { System.out.println(cdt[i]);}
    }
    catch(Exception e)
    { e.printStackTrace();}
  }
}

public Student() public Student(java.lang.String) public Student() public Student(java.lang.String)

getMethods() and getDeclaredMethods()

getMethods() method returns array of Method object that reflect all the public method of invoking object. getDeclaredMethods() returns only the declared methods of the invoking class object. Syntax for both is following,

Method< ?>[] getMethods();
Method< ?>[] getDeclaredMethods();

Example: getDeclaredMethods() method

Lets take an example in which we are using getDeclaredMethods() method to get all the declared methods in the class. See the below example.

import java.lang.reflect.*;
class Student
{
  public void show(){}
  void display(){}
}

class Test
{
  public static void main(String args[])
  {
    try
    {
      Class c = Class.forName("Student");
      Method md[] = c.getDeclaredMethods();
      for(int i=0; i< md.length; i++ )
      { System.out.println(md[i]); }
    }
    catch(Exception e)
    { e.printStackTrace();}
  }
}

public void Student.show() void Student.display()

getFields() and getDeclaredFields()

getFields() returns an array containing Field objects reflecting all the accessible public members of the class or interface represented by this Class object. getDeclaredFields() returns array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.

Field< ?>[] getFields();
Field< ?>[] getDeclaredFields();

Example: getFields() and getDeclaredFields() method

To get fields of a class, we can use either getFields() or getDeclaredFields() method. Both returns fields except that getFields returns only public fields. See the below example.

import java.lang.reflect.*;
class Student
{
  public  String name;
  int roll;
}

class Test
{
  public static void main(String args[])
  {
    try
    {
      Class c = Class.forName("Student");
      Field ff[] = c.getFields();
      for(int i=0; i< ff.length; i++)
      { System.out.println(ff[i]); }
      Field f[] = c.getDeclaredFields();
      for(int i=0;i< f.length; i++)
      { System.out.println(f[i]);  }
    }
    catch(Exception e)
    { e.printStackTrace();}
  }
}

public java.lang.String Student.name public java.lang.String Student.name int Student.roll