Sunday, August 31, 2014
Java reflection is an advanced feature and is the ability to examine or modify the run-time behavior of applications.  Java reflection is primarily used in applications like test tools, debuggers, class browsers etc.

Reflection provides the ability to examine private members of a class and also has associated performance overhead since the types are dynamically resolved. Java reflection techniques need to be used only when it is absolutely necessary.

This article provides a quick introduction to Java reflection with examples.

Class Objects

Entry for all reflection operations is the java.lang.Class object. There are several approaches to get access to the Class object.
  • If we have an instance of an object the Class object can be obtained by simply doing Object.getClass().
  • If we don't have access to an instance of the object and the type is available then we can get Class object by appending .class to type name.
  • If we have the fully qualified name of the class then we get Class instance by using the static method Class.forName().
Let us consider a simple Employee class which we are using reflection to examine.

package com.sourcetricks.reflection;

@Author(name="SourceTricks")
public class Employee {
  private int id;
  private String name;

  Employee(int id, String name) {
    this.id = id;
    this.name = name;
  }
  public int getId() {
    return id;
  }
  public String getName() {
    return name;
  }
  public void setId(int id) {
    this.id = id;
  }
  public void setName(String name) {
    this.name = name;
  }
}

To get access to the Class object one of the above listed approaches could be used as in this example.

public static void main(String[] args) throws Exception {
  
  // Get class object using an Employee object
  Employee e = new Employee(10, "Name");
  Class<?> c1 = e.getClass(); 
  
  // Get class object using .class to the name of type
  Class<?> c2 = Employee.class;
  
  // Get class object by using static method Class.forName()
  Class<?> c = Class.forName("com.sourcetricks.reflection.Employee");
}

Java Reflection Example

Once we have access to the Class object then we can examine the class modifiers, methods, fields, constructors, annotations etc. The custom annotation used on the Employee class needs to have RetentionPolicy as RUNTIME so that it can be examined via reflection. Please refer to Java Annotations tutorial for more examples.

@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
   String name();
}

In the code snippet below we examine the previously created Employee class using reflection.

public static void main(String[] args) throws Exception {
  
  // Get class object by using static method Class.forName()
  Class <?> c = Class.forName("com.sourcetricks.reflection.Employee");
   
  // Get package name
  System.out.println("Package name: " + c.getPackage());
  
  // Get canonical name
  System.out.println("Canonical name: " + c.getCanonicalName());
  
  // Get declared methods and it parameter types
  System.out.println("---- Methods and parameters ----");
  Method[] methods = c.getDeclaredMethods();
  for ( Method m : methods ) {      
    System.out.println("--" + m.getName() + "--");
    Class<?>[] params = m.getParameterTypes();
    for ( Class<?> p : params ) {
      System.out.println(p.getName());
    }
  }
  
  // Get class modifiers
  int modifier = c.getModifiers();
  System.out.println("---- Modifiers ----");
  System.out.println(Modifier.toString(modifier));
  
  // Get class declared members
  Field[] fields = c.getDeclaredFields();
  System.out.println("---- Fields, names and types ----");
  for ( Field f : fields ) {
    Class<?> t = f.getType();
    System.out.println(f.getName() + " " + t.getName());
  }
  
  // Get constructors
  Constructor<?>[] constructors = c.getDeclaredConstructors();
  System.out.println("---- Constructors ----");
  for ( Constructor<?> cons : constructors ) {
    System.out.println(cons.getName());
  }
  
  // Get Annotations
  Annotation[] annotations = c.getDeclaredAnnotations();
  System.out.println("---- Annotations ----");
  for ( Annotation a : annotations ) {
    System.out.println(a.toString());
  }
  
  // Invoke a method
  Method method = e.getClass().getMethod("setId", int.class);
  method.invoke(e, 20);
  System.out.println(e.getId());
}

This program produces the following output.

Package name: package com.sourcetricks.reflection
Canonical name: com.sourcetricks.reflection.Employee
---- Methods and parameters ----
--getName--
--getId--
--setName--
java.lang.String
--setId--
int
---- Modifiers ----
public
---- Fields, names and types ----
id int
name java.lang.String
---- Constructors ----
com.sourcetricks.reflection.Employee
---- Annotations ----
@com.sourcetricks.reflection.Author(name=SourceTricks)
20

Continue to read other Java Tutorials.

1 comment :

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top