StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Sunday, August 31, 2014

Java Reflection Tutorial

 August 31, 2014     Java     No comments   

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.
  • Share This:  
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Implement caching in a Spring Boot microservice using Redis
    In this article we will explore how to use Redis as a data cache for a Spring Boot microservice using PostgreSQL as the database. Idea is to...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Spring Boot with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Getting started with Kafka in Python
    This article will provide an overview of Kafka and how to get started with Kafka in Python with a simple example. What is Kafka? ...
  • Getting started in GraphQL with Spring Boot
    In this article we will explore basic concepts on GraphQL and look at how to develop a microservice in Spring Boot with GraphQL support. ...

Copyright © StackStalk