Showing posts with label Java reflection. Show all posts
Showing posts with label Java reflection. Show all posts

Tuesday, April 2, 2024

Reflection in Java - Getting Method Information

Reflection in Java class gives a good idea about how class is an entry point to all the Reflection APIs. Once you have Class object you can get information about members of the class like fields, constructors, methods. In this post we'll see how you can get method information using Java Reflection API.


Member Interface in Java Reflection API

With in the Reflection hierarchy an interface java.lang.reflect.Member is defined which is implemented by java.lang.reflect.Field, java.lang.reflect.Method, and java.lang.reflect.Constructor classes. Thus Member is an interface that provides identifying information about a single member (a field or a method) or a constructor.

This post talks about Method class and how it can be used to get information about methods using reflection. Class methods have return values, parameters, and may throw exceptions. The java.lang.reflect.Method class provides methods for obtaining the type information for the parameters and return value. It may also be used to invoke methods on a given object.

How to get Method object

Once you have instance of the Class you can use any of the following 4 methods for getting information about methods of the 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.
  • 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.
  • 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.
  • 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.

Getting method information using Java reflection example

As a preparation for the example code let’s have a class called Parent.java which will be extended by the class ChildClass.java which is the class we are going to examine. There is also an interface IntTest.java which is implemented by ChildClass.java.

Parent class

public class Parent {
  String name;
  Parent(String name){
    this.name = name;
  }
  public void displayName(String name){
    System.out.println("Hello - " + name);
  }  
  public String getName(){
    return name;
  }
}

IntTest interface

public interface IntTest {
 public void showValue();
}

ChildClass.java

public class ChildClass extends Parent implements IntTest{
 private int value;
 //Constructor
 public ChildClass(String name, int value) {
  super(name);
  this.value = value;
 }

 @Override
 public void showValue() {
  System.out.println("Value - " + value);  
 }
}

Now let’s see how you can get method information using all the four methods mentioned above.

import java.lang.reflect.Method;
import java.util.Arrays;

public class ReflectMethod {
  public static void main(String[] args) {
    try {
      // Getting Class instance
      Class<?> c = Class.forName("org.netjs.prog.ChildClass");
            
      // Using getMethod(methodName, parameters)
      Method method = c.getMethod("displayName", String.class);
      System.out.println("Method params " + Arrays.toString(method.getParameters()));
            
      // Will throw exception
      /*method = c.getDeclaredMethod("displayName", String.class);
      System.out.println("Method params " + Arrays.toString(method.getParameters()));*/
            
      Method[] methodArr = c.getMethods();
      System.out.println("All methods " + Arrays.toString(methodArr));
            
      methodArr = c.getDeclaredMethods();
      System.out.println("Class methods " + Arrays.toString(methodArr));
            
    } catch (ClassNotFoundException | NoSuchMethodException | SecurityException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Output

Method params [java.lang.String arg0]

All methods [public void org.netjs.prog.ChildClass.showValue(), public java.lang.String org.netjs.prog.Parent.getName(), 
public void org.netjs.prog.Parent.displayName(java.lang.String), 
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()]

Class methods [public void org.netjs.prog.ChildClass.showValue()]

First call to the getMethod with parameters method name and parameter types returns the matching method. Then parameters of the method are printed using the getParameters() method of the Method class.

Second call (Which is commented) will throw NoSuchMethodException as the method displayName is inherited from the parent class and getDeclaredMethod() will work for the methods with in the class.

getMethods() will return all the methods of the class and also the inherited methods.

GetDeclaredMethods() will return all the methods of the class but not the inherited one.

Getting method parameter types and return type using reflection

If we have a class called ChildClass as follows then we can get its method parameter types and return type using reflection.

ChildClass.java

public class ChildClass extends Parent implements IntTest{
 private int value;
 //Constructor
 public ChildClass(String name, int value) {
  super(name);
  this.value = value;
 }

 @Override
 public void showValue() {
  System.out.println("Value - " + value);  
 }
 
 public String getValue(String name) throws Exception{
  return "Hello" + name;
 }
}
// Getting Class instance
Class<?> c = Class.forName("org.netjs.prog.ChildClass");
methodArr = c.getDeclaredMethods();
for(Method m: methodArr){
  System.out.println("For Method - " + m.getName() + " Parameter types are - " + Arrays.toString(m.getParameterTypes()));
  System.out.println("For Method - " + m.getName() + " Return type " + m.getReturnType());
}

Output

For Method - getValue Parameter types are - [class java.lang.String]
For Method - getValue Return type class java.lang.String
For Method - showValue Parameter types are - []
For Method - showValue Return type void

Getting method modifiers using reflection

If you want to get information about the modifiers of the methods of the class you can use getModifiers() method whose return type is int.

// Getting Class instance
Class<?> c = Class.forName("org.netjs.prog.ChildClass");
methodArr = c.getDeclaredMethods();
for(Method m: methodArr){
  System.out.println("For Method - " + m.getName() + 
    " modifier is - " + Modifier.toString(m.getModifiers()));
}

Output

For Method - getValue modifier is – public
For Method - showValue modifier is – public

Getting thrown exceptions using reflection

If you want to get information about types of exceptions declared to be thrown by the methods of the class you can use getExceptionTypes() method.

// Getting Class instance
Class<?> c = Class.forName("org.netjs.prog.ChildClass");
methodArr = c.getDeclaredMethods();
for(Method m: methodArr){
  System.out.println("For Method - " + m.getName() + " Thrown Exceptions  - " 
    + Arrays.toString(m.getExceptionTypes()));
}

Output

For Method - getValue Thrown Exceptions  - [class java.lang.Exception]
For Method - showValue Thrown Exceptions  - []

Invoking method using reflection

Using Java reflection API you can also invoke methods on a class at runtime. Methods are invoked using java.lang.reflect.Method.invoke() method. The first argument is the object instance on which this particular method is to be invoked. (If the method is static, the first argument should be null.) Subsequent arguments are the method's parameters.

// Getting Class instance
Class<?> c = Class.forName("org.netjs.prog.ChildClass");
// Getting class object
ChildClass ch = new ChildClass("Test", 10);
Method method = c.getDeclaredMethod("getValue", String.class);
try {
  String result = (String)method.invoke(ch, "Reflection");
  System.out.println("Method invocation returned - " + result);
} catch (IllegalAccessException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
} catch (IllegalArgumentException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
} catch (InvocationTargetException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

Output

Method invocation returned – HelloReflection

Invoking private method of the class using reflection

You can even invoke the private methods of the class using Reflection in Java. Using getDeclaredMethod() you can get the private methods of the class.

Once you have the method object you can use the setAccessible() method which is inherited from class java.lang.reflect.AccessibleObject to set the access for the private method as true at run time and then invoke it from another class.

Let’s say we have a ChildClass as follows with a private method getValue().

public class ChildClass extends Parent implements IntTest{
  private int value;
  //Constructor
  public ChildClass(String name, int value) {
    super(name);
    this.value = value;
  }

  @Override
  public void showValue() {
    System.out.println("Value - " + value);  
  }
 
  private String getValue(String name) throws Exception{
    return "Hello" + name;
  }
}

Now you want to invoke this private method.

// Getting Class instance
Class<?> c = Class.forName("org.netjs.prog.ChildClass");
// Getting class object
ChildClass ch = new ChildClass("Test", 10);
Method method = c.getDeclaredMethod("getValue", String.class);
method.setAccessible(true);
try {
    String result = (String)method.invoke(ch, "Reflection");
    System.out.println("Method invocation returned - " + result);
} catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IllegalArgumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (InvocationTargetException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Output

Method invocation returned – HelloReflection

You can comment the line where access to the method is set as true.

//method.setAccessible(true);

Then if you execute it you will get the exception as follows -

java.lang.IllegalAccessException: Class org.netjs.prog.ReflectMethod can not access a member of class 
org.netjs.prog.ChildClass with modifiers "private"
 at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
 at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(Unknown Source)
 at java.lang.reflect.AccessibleObject.checkAccess(Unknown Source)
 at java.lang.reflect.Method.invoke(Unknown Source)
 at org.netjs.prog.ReflectMethod.main(ReflectMethod.java:32)

That's all for this topic Reflection in Java - Getting Method Information. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Reflection in Java - Getting Field Information
  2. Reflection in Java - Getting Constructor Information
  3. Reflection in Java - Array
  4. Generating Getters And Setters Using Reflection in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Externalizable Interface in Java
  2. Java Concurrency Interview Questions And Answers
  3. FlatMap in Java
  4. Method Reference in Java
  5. Wildcard in Java Generics
  6. Race Condition in Java Multi-Threading
  7. Switch Case Statement in Java With Examples
  8. static Block in Java

Sunday, March 3, 2024

Generating Getters And Setters Using Reflection in Java

When you right click on any Java Bean class name with in the eclipse IDE and click on Source – Generate Getters and Setters you get the getter and setter methods for the selected fields. Ever wondered what goes in the background to generate the getter and setter methods programmatically?

Yes, it is the magic of reflection in Java which gets the information about the fields of the class and their types and then generate the getters and setters using reflection accordingly.

If you have to create such a functionality yourself then using the Java Reflection API you can create your own getters and setters generator class, of course just for academic purpose, as all the IDEs anyway provide the facility to do that.

Getters & Setters generator using reflection example

Let’s say you have a class TestClass with three fields of type int, String and Boolean and you want to generate getters and setters for these 3 fields using Java reflection API.

TestClass

public class TestClass {
 private int value;
 private String name;
 private boolean flag;
} 

GetterSetterGenerator class

Using the Reflection API for the field you can get information about the fields of the given class – like name and type. Once you have that information you can create set and get methods for the fields. In this code set and get methods are just printed after creating them as it is just for illustrating the usage of reflection in Java so not going into File I/O.

import java.lang.reflect.Field;
import java.util.Arrays;

public class GetterSetterGenerator {

 public static void main(String[] args) {
  try {
   GetterSetterGenerator gt = new GetterSetterGenerator();
   StringBuffer sb = new StringBuffer();
   
   Class<?> c = Class.forName("org.prgm.TestClass");
   // Getting fields of the class
   Field[] fields = c.getDeclaredFields();
   System.out.println("Fields - " + Arrays.toString(fields));
   for(Field f : fields){
    String fieldName = f.getName();
    String fieldType = f.getType().getSimpleName();
    
    System.out.println("Field Name -- " + fieldName);
    System.out.println("Field Type " + fieldType);
    
    gt.createSetter(fieldName, fieldType, sb);    
    gt.createGetter(fieldName, fieldType, sb);
   }
   System.out.println("" + sb.toString());
   
  }catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  
 }

 private void createSetter(String fieldName, String fieldType, StringBuffer setter){
  setter.append("public void").append(" set");
  setter.append(getFieldName(fieldName));
  setter.append("(" + fieldType + " " + fieldName + ") {");
  setter.append("\n\t this."+ fieldName + " = " + fieldName + ";");
  setter.append("\n" + "}" + "\n");
 }
 
 private void createGetter(String fieldName, String fieldType, StringBuffer getter){
  // for boolean field method starts with "is" otherwise with "get"
  getter.append("public " + fieldType).append((fieldType.equals("boolean")?" 
    is" : " get") + getFieldName(fieldName) + "(){");
  getter.append("\n\treturn " + fieldName + ";");
  getter.append("\n" + "}" + "\n");
 }
 
 private String getFieldName(String fieldName){
  return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(
    1, fieldName.length());
 }
}

Output

Fields - [private int org.prgm.TestClass.value, private java.lang.String org.prgm.TestClass.name, private boolean org.prgm.TestClass.flag]
Field Name -- value
Field Type int
Field Name -- name
Field Type String
Field Name -- flag
Field Type Boolean

public void setValue(int value) {
  this.value = value;
}
public int getValue(){
 return value;
}
public void setName(String name) {
  this.name = name;
}
public String getName(){
 return name;
}
public void setFlag(boolean flag) {
  this.flag = flag;
}
public boolean isFlag(){
 return flag;
}

That's all for this topic Generating Getters And Setters Using Reflection in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Invoking Getters And Setters Using Reflection in Java
  2. Reflection in Java - Getting Class Information
  3. Reflection in Java - Getting Method Information
  4. How to Pass Command Line Arguments in Eclipse
  5. How to Compile Java Program at Runtime

You may also like-

  1. Remove Duplicate Elements From an Array in Java
  2. Format Date in Java Using SimpleDateFormat
  3. Read or List All Files in a Folder in Java
  4. Nested class and Inner class in Java
  5. Externalizable interface in Java
  6. Constructor Chaining in Java
  7. Parallel Stream in Java Stream API
  8. Method Reference in Java

Monday, June 12, 2023

Invoking Getters And Setters Using Reflection in Java

In the post reflection in java – method it is already explained how you can invoke a method of the class at runtime. In this post we’ll use that knowledge to invoke getters and setters of the class using Java reflection API. In Java you can do it using two ways.

In this post we'll see example of both of these ways to invoke getters and setters of the class.

Using PropertyDescriptor class

A PropertyDescriptor describes one property that a Java Bean exports via a pair of accessor methods. Then using the getReadMethod() and getWriteMethod() you can call the setter and getter for the property.

Invoking getters and setters using PropertyDescriptor example

Here in the example we have a class TestClass which has getter and setter for three fields which are of type int, String and boolean. Then in the GetterAndSetter class there are methods to invoke the getters and setters of the given class.

TestClass.java

package org.prgm;

public class TestClass {
 private int value;
 private String name;
 private boolean flag;
 public int getValue() {
  return value;
 }
 public void setValue(int value) {
  this.value = value;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public boolean isFlag() {
  return flag;
 }
 public void setFlag(boolean flag) {
  this.flag = flag;
 }
}

GetterAndSetter.java

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class GetterAndSetter {
 public static void main(String[] args) {
  GetterAndSetter gs = new GetterAndSetter();
  TestClass tc = new TestClass();
  gs.callSetter(tc, "name", "John");
  gs.callSetter(tc, "value", 12);
  gs.callSetter(tc, "flag", true);
  // Getting fields of the class
  Field[] fields = tc.getClass().getDeclaredFields();
  
  for(Field f : fields){
   String fieldName = f.getName();
   System.out.println("Field Name -- " + fieldName);
  }
  gs.callGetter(tc, "name");
  gs.callGetter(tc, "value");
  gs.callGetter(tc, "flag");
 }
 
 private void callSetter(Object obj, String fieldName, Object value){
  PropertyDescriptor pd;
  try {
   pd = new PropertyDescriptor(fieldName, obj.getClass());
   pd.getWriteMethod().invoke(obj, value);
  } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 private void callGetter(Object obj, String fieldName){
  PropertyDescriptor pd;
  try {
   pd = new PropertyDescriptor(fieldName, obj.getClass());
   System.out.println("" + pd.getReadMethod().invoke(obj));
  } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Output

Field Name -- value
Field Name -- name
Field Name -- flag
John
12
true

Scanning methods of the class and look for set and get methods

Another way to invoke the getters and setters using Java reflection is to scan all the methods of the class through reflection and then find out which are the getters and setters method.

It is particularly useful to use this way to call get methods if you have lots of fields in a class. Calling set method that way won’t be of much help as you will have to still invoke individual method with the value that has to be set.

Logic to identify get method

get method starts with get or is (in case of boolean), it should not have any parameters and it should return a value.

Logic to identify set method

set method starts with set and it should have a parameter and it shouldn't return any value which means it should return void.

In the example same Java bean class as above TestClass is used.

In the GetterAndSetter class there are methods to identify the getters and setters of the given class. If it is a get method that is invoked to get the value. For set method invocation is done to set the property values.

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class GetterAndSetter {
  public static void main(String[] args) {
    TestClass tc = new TestClass();
    // get all the methods of the class
    Method[] methods = tc.getClass().getDeclaredMethods();
    // Initially calling all the set methods to set values
    for(Method method : methods){
      if(isSetter(method)){
        System.out.println("Setter -- " + method.getName());
        try {
          if(method.getName().contains("Name")) {
            method.invoke(tc, "John");
          } 
          if(method.getName().contains("Value")) {
            method.invoke(tc, 12);
          }
          if(method.getName().contains("Flag")) {
            method.invoke(tc, true);
          }
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }    
      }
    }
    // calling getters
    for(Method method : methods){
      if(isGetter(method)){
        try {
          Object obj = method.invoke(tc);
          System.out.println("Invoking "+ method.getName() + " Returned Value - " + obj);
        } catch (IllegalAccessException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (IllegalArgumentException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (InvocationTargetException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }   
    }
  }

  private static boolean isGetter(Method method){
    // identify get methods
    if((method.getName().startsWith("get") || method.getName().startsWith("is")) 
        && method.getParameterCount() == 0 && !method.getReturnType().equals(void.class)){
      return true;
    }
    return false; 
  }

  private static boolean isSetter(Method method){
    // identify set methods
    if(method.getName().startsWith("set") && method.getParameterCount() == 1 
        && method.getReturnType().equals(void.class)){
      return true;
    }
    return false; 
  }
}

Output

Setter -- setName
Setter -- setValue
Setter -- setFlag
Invoking getName Returned Value - John
Invoking getValue Returned Value - 12
Invoking isFlag Returned Value - true

That's all for this topic Invoking Getters And Setters Using Reflection in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Generating Getters And Setters Using Reflection in Java
  2. Java Reflection API Tutorial
  3. Reflection in Java - Getting Class Information
  4. Reflection in Java - Getting Field Information
  5. Reflection in Java - Getting Constructor Information

You may also like-

  1. How to Sort Elements in Different Order in TreeSet
  2. Java Lambda Expression Callable Example
  3. How to Run a Shell Script From Java Program
  4. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example
  5. Java Stream API Examples
  6. How to Fix The Target Type of This Expression Must be a Functional Interface Error
  7. PermGen Space Removal in Java 8
  8. Marker Interface in Java

Sunday, December 4, 2022

Reflection in Java - Getting Constructor Information

Similar to reflection API for methods, there is also reflection API to get information about the constructors of a class. Using java.lang.reflect.Constructor class in Java reflection API you can get information about the modifiers, parameters, annotations, and thrown exceptions. You can also create a new instance of a class using a specified constructor.

How to get Constructor object using reflection

As always the starting point is the Class and there are four methods provided by the class Class for getting the constructors.

  • getConstructor(Class<?>... parameterTypes)- 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.
  • getConstructors()- Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.
  • getDeclaredConstructor(Class<?>... parameterTypes)– Returns a Constructor object that reflects the specified constructor of the class or interface 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.
  • getDeclaredConstructors()- Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object. These are public, protected, default (package) access, and private constructors.

Getting constructor information using reflection Java example

For example we’ll be using this class TestClass which has one public constructor with 2 args and a private constructor.

TestClass.java

public class TestClass {
 private int value;
 private String name;
 // public Constructor
 public TestClass(int value, String name) {  
  this.value = value;
 }
 // private constructor
 private TestClass() {
 
 }
 
 public void showValue() {
  System.out.println("Value - " + value);
 }
}

If you want to get constructors using the above 4 methods it can be done as follows–

import java.lang.reflect.Constructor;
import java.util.Arrays;

public class ReflectConstructor {

 public static void main(String[] args) {
  try {
   Class<?> c = Class.forName("org.prgm.TestClass");
   // To get constructor with 2 args
   Constructor<?> constructor = c.getConstructor(int.class, String.class);
   //Constructor<?> constructor = c.getConstructor(new Class[]{int.class, String.class});
   
   System.out.println("constructor " + constructor.toString());
   // to get private constructor using getDeclaredConstructor() method
   constructor = c.getDeclaredConstructor();
   System.out.println("constructor " + constructor.toString());
   
   // Getting constructors of the class
   Constructor<?>[] constructors = c.getConstructors();
   System.out.println("Constructors - " + Arrays.toString(constructors));
   
   Constructor<?>[] Decconstructors = c.getDeclaredConstructors();
   System.out.println("Declared constructors - " + Arrays.toString(Decconstructors));
  } catch (ClassNotFoundException | NoSuchMethodException | SecurityException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

Output

constructor public org.prgm.TestClass(int,java.lang.String)
constructor private org.prgm.TestClass()
Constructors - [public org.prgm.TestClass(int,java.lang.String)]
Declared constructors - [public org.prgm.TestClass(int,java.lang.String), private org.prgm.TestClass()]

Here note that in the first call two parameters are passed with the getConstructor() method which match the arguments of the constructor in the TestClass class. Since parameter is defined as varargs in getConstructor() so you can pass as comma separated parameters or as an array of class objects. Which is done as an illustration in the commented code.

Second call uses the getDeclaredConstructor(); method as that can return constructor object pertaining to private constructor too.

Same way getDeclaredConstructors() method returns an array of Constructor objects reflecting all the constructors of the class public or private where as getConstructors() method returns an array of constructor objects reflecting all the public constructors of the class.

Class<?> c = Class.forName("org.prgm.TestClass");
Constructor<?>[] Decconstructors = c.getDeclaredConstructors();
for(Constructor<?> ctr : Decconstructors){
 System.out.println("Constructor -- " + ctr.getName());
 Class<?>[] pType  = ctr.getParameterTypes();
 for (int i = 0; i < pType.length; i++) {
  System.out.println("Parameter -- " + pType[i]);
 }
}

Getting modifiers of the constructors using reflection

You can get modifiers of the constructors of the class through reflection using getModifiers() method.

Class<?> c = Class.forName("org.prgm.TestClass");
Constructor<?>[] Decconstructors = c.getDeclaredConstructors();
for(Constructor<?> ctr : Decconstructors){
 System.out.println("Constructor -- " + ctr.getName() + " has modifier " 
  +  Modifier.toString(ctr.getModifiers()));
}

Output

Constructor -- org.prgm.TestClass has modifier public
Constructor -- org.prgm.TestClass has modifier private

Creating class instance using reflection

In reflection API there are two methods for creating instances of classes- java.lang.reflect.Constructor.newInstance() and Class.newInstance(). It is preferable to go with the one provided by the Constructor class for the reasons explained here-

  1. Class.newInstance() can only invoke the zero-argument constructor, while Constructor.newInstance() may invoke any constructor, regardless of the number of parameters.
  2. Class.newInstance() requires that the constructor be visible;
    Constructor.newInstance() can invoke private constructors also by setting accessibility to true.
  3. Class.newInstance() throws any exception thrown by the constructor whether it is checked or unchecked exception.
    Constructor.newInstance() always wraps the thrown exception with an InvocationTargetException.

For the TestClass.java which has one public constructor with two arguments and one no-arg private constructor, creating new class instances can be done as follows.

Class<?> c = Class.forName("org.prgm.TestClass");
Constructor<?>[] Decconstructors = c.getDeclaredConstructors();
for(Constructor<?> ctr : Decconstructors){
  System.out.println("Constructor -- " + ctr.getName());
  try {
    TestClass t;
    if(Modifier.toString(ctr.getModifiers()).equals("private")){
      // Setting accessibility to true if it's a private constructor
      ctr.setAccessible(true);
      t = (TestClass)ctr.newInstance();
    }else{
      t = (TestClass)ctr.newInstance(100, "InstanceTest");
    }   
    t.showValue();
  } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
    e.printStackTrace();
  }   
}

Output

Constructor -- org.prgm.TestClass
Value - 100
Constructor -- org.prgm.TestClass
Value – 0

In the code there is a check for the modifier of the constructor. If it is private then the set the accessible flag to true, with that even private constructor can be accessed from another class and an instance created.

That's all for this topic Reflection in Java - Getting Constructor Information. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Reflection in Java - Getting Class Information
  2. Reflection in Java - Getting Field Information
  3. Generating Getters And Setters Using Reflection in Java
  4. Serialization and Deserialization in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. How ArrayList Works Internally in Java
  2. TreeSet in Java With Examples
  3. ConcurrentHashMap in Java With Examples
  4. Java ReentrantReadWriteLock With Examples
  5. Volatile Keyword in Java With Examples
  6. Lambda Expressions in Java 8
  7. Difference Between Encapsulation And Abstraction in Java
  8. super Keyword in Java With Examples

Thursday, September 1, 2022

Reflection in Java - Array

In this post you'll see how you can manipulate an array using Reflection API in Java. Array in Java is also a class so many of the methods in java.lang.Class may be used with the array.

Reflection in Java also provides a specific class java.lang.reflect.Array for arrays. In this post we'll see how you can get information about Array using Reflection API.

How to identify array using reflection

If you want to determine if a class member is a field of array type that can be done by invoking Class.isArray() method.

For example let’s say we have a class TestClass which has one array field numArray. In another class ReflectArray using the class.isArray() method it is determined if there is any array in the TestClass.

TestClass

public class TestClass {
 private int value;
 private int[] numArray;
 public int getValue() {
  return value;
 }
 public void setValue(int value) {
  this.value = value;
 }
 public int[] getNumArray() {
  return numArray;
 }
 public void setNumArray(int[] numArray) {
  this.numArray = numArray;
 }
}

ReflectArray

import java.lang.reflect.Field;

public class ReflectArray {
  public static void main(String[] args) {
    try {
      Class<?> c = Class.forName("org.netjs.prog.TestClass");
      Field[] fields = c.getDeclaredFields();
      for (Field f : fields) {
        Class<?> type = f.getType();
        // Looking for array
        if(type.isArray()){
          System.out.println("Array found " + f.getName());
        }
      }            
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Output

Array found numArray

Creating new array using Java reflection

Using reflection API in Java you can dynamically create arrays of arbitrary type and dimensions using java.lang.reflect.Array.newInstance() method.

int[] testArray = (int[])Array.newInstance(int.class, 5);
System.out.println("length of array " + testArray.length);

Output

length of array 5

Getting and setting array using reflection

Using Java reflection API you can get or set an entire array. You can set an entire array using Field.set(Object obj, Object value) method. To retrieve an entire array use Field.get(Object obj) method.

If you want to get or set an array individual element by element, Array class has methods for that also. In order to set or get an int array you can use setInt(Object array, int index, int i) and getInt(Object array, int index) methods. Same way if you have a float array you can use setFloat(Object array, int index, float f) and getFloat(Object array, int index) methods.

There is also a method which takes Object for value as parameter that can be used with any type- set(Object array, int index, Object value) and get(Object array, int index) methods.

int[] testArray = (int[])Array.newInstance(int.class, 5);
System.out.println("length of array " + testArray.length);
// Setting values using setInt and set methods
Array.setInt(testArray, 0, 1);
Array.set(testArray, 1, 2);
Array.setInt(testArray, 2, 3);

// Getting values using getInt and get methods
System.out.println("First element " + Array.get(testArray, 0));
System.out.println("Second element " + Array.getInt(testArray, 1));
System.out.println("Third element " + Array.getInt(testArray, 2));

Output

length of array 5
First element 1
Second element 2
Third element 3

That's all for this topic Reflection in Java - Array. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Reflection in Java - Getting Field Information
  2. Reflection in Java - Getting Method Information
  3. Reflection in Java - Getting Constructor Information
  4. Generating Getters And Setters Using Reflection in Java
  5. Invoking Getters And Setters Using Reflection in Java

You may also like-

  1. How to Pass Command Line Arguments in Eclipse
  2. Nested class and Inner class in Java
  3. BigDecimal in Java With Examples
  4. SerialVersionUID And Versioning in Java Serialization
  5. Type Erasure in Java Generics
  6. AutoBoxing and UnBoxing in Java
  7. Is String Thread Safe in Java
  8. CopyOnWriteArrayList in Java With Examples

Saturday, March 12, 2022

Java Reflection API Tutorial

As per Wikipedia; in computer science, reflection is the ability of a computer program to examine, introspect, and modify its own structure and behavior at runtime. Thus the Reflection API in Java provides the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.

Using Reflection in Java you can inspect a class and get information about the fields, methods, constructors, implemented interfaces, super classes at run time, you can even invoke a method at run time. Using reflection you can also dynamically create and access Java arrays, examine the Enums, you can even access a private field and invoke a private method from another class!


Where is Reflection API used

Though you may not have a need to use reflection API in your application but you may be seeing its usage in many tools or applications you are using.

  1. The IDE like Eclipse giving you the list of methods in a class, auto completing the field or method name.
  2. Your persistence framework matching the fields in your objects with the fields in the DB table at runtime.
  3. Junit getting the information about the methods to be invoked.
  4. Spring framework getting the class information using the bean definition and also getting the setters and getters or constructor of the class. So you can say dependency injection in Spring depends heavily on reflection.

Reflection API in Java

Some of the main classes and interfaces which you will use while using reflection in Java are as follows–

  • Class- For every type of object, JVM instantiates an immutable instance of java.lang.Class (Note that Class itself is not part of Reflection API) which provides methods to examine the runtime properties of the object including its members and type information. Class also provides the ability to create new classes and objects. Most importantly, it is the entry point for all of the Reflection APIs. Refer Reflection in Java - Class to see examples of getting information about any class at run time.
  • Member- Reflection defines an interface java.lang.reflect.Member which is implemented by java.lang.reflect.Field, java.lang.reflect.Method, and java.lang.reflect.Constructor which can be used to get information about class members.
  • Field- Field class provides methods for accessing type information and setting and getting values of a field on a given object. To see examples of using Field class refer this post- Reflection in Java - Field.
  • Method- Method class provides methods for obtaining the type information for the parameters and return value. It may also be used to invoke methods on a given object. To see examples of using Method class refer this post- Reflection in Java - Method.
  • Constructor- Constructor class provides methods for obtaining the information about the constructors of the class. If you reflectively invoke a constructor it will create a new instance of an object for a given class. To see examples of using Constructor class refer this post- Reflection in Java - Constructor.
  • Array- The Array class provides static methods to dynamically create and access Java arrays. Reflection provides methods for accessing array types and array component types, creating new arrays, and retrieving and setting array component values. To see examples of using Array class refer this post- Reflection in Java - Array.

Java Reflection Example code

Here is an example of Java Reflection API to get an idea about how to use it. There is a class ClassA which has a constructor, private fields and getters and setters.

package org.prgm;

public class ClassA {
 private int i;
 private int j;
 // Constructor
 public ClassA(int i, int j){
  this.i = i;
  this.j = j;
 }
 public void setI(int i) {
  this.i = i;
 }
 public void setJ(int j) {
  this.j = j;
 }
 public int getI() {
  return i;
 }
 public int getJ() {
  return j;
 }
}

Using the following class you can get information about the constructor of the class, fields of the class and class methods.

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

public class ReflectionDemo {

 public static void main(String[] args) {
  try {
   Class<?> c = Class.forName("org.prgm.ClassA");
   // Getting constructors of the class
   Constructor<?>[] constructors = c.getConstructors();
   System.out.println("Constructors - " + Arrays.toString(constructors));
   
   // Getting all methods (even inherited) of the class
   Method[] methods = c.getMethods();
   System.out.println("All Methods - " + Arrays.toString(methods));
   
   // Getting methods of the class
   methods = c.getDeclaredMethods();
   System.out.println("Class Methods - " + Arrays.toString(methods));
   
   // Getting fields of the class
   Field[] fields = c.getDeclaredFields();
   System.out.println("Fields - " + Arrays.toString(fields));
   
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  
 }
}

Output

Constructors - [public org.prgm.ClassA(int,int)]

All Methods - [public int org.prgm.ClassA.getI(), public void org.prgm.ClassA.setI(int), public void org.prgm.ClassA.setJ(int), 
public int org.prgm.ClassA.getJ(), 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()]

Class Methods - [public int org.prgm.ClassA.getI(), public void org.prgm.ClassA.setI(int), public void org.prgm.ClassA.setJ(int), 
public int org.prgm.ClassA.getJ()]

Fields - [private int org.prgm.ClassA.i, private int org.prgm.ClassA.j]

Drawbacks of Reflection in Java

Reflection provides a lot of power so it should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. Some of the drawbacks of Reflection are-

  1. Performance Overhead– Since reflection resolves types dynamically certain JVM optimizations can’t be performed. Thus the reflective operations have slower performance than their non-reflective counterparts. That means use of reflection in the sections of code which are called frequently in performance-sensitive applications should be avoided.
  2. Security Restrictions- Reflection requires a runtime permission which may not be present when running under a security manager. Thus the code which has to run in a restricted security context should avoid reflection.
  3. Against Object oriented principles- Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.

Reference- https://docs.oracle.com/javase/tutorial/reflect/index.html

That's all for this topic Java Reflection API Tutorial. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Reflection in Java - Getting Method Information
  2. Reflection in Java - Getting Constructor Information
  3. Generating Getters And Setters Using Reflection in Java
  4. Java Object Cloning - clone() Method
  5. Serialization and Deserialization in Java

You may also like-

  1. instanceof Operator in Java
  2. BigDecimal in Java With Examples
  3. Try-With-Resources in Java With Examples
  4. Primitive Type Streams in Java Stream API
  5. Lambda Expressions in Java 8
  6. PermGen Space Removal in Java 8
  7. Generics in Java
  8. How HashMap Works Internally in Java

Thursday, March 10, 2022

Reflection in Java - Getting Class Information

In this post we'll see how to use Reflection in Java to get information about any class at run time.

For every type of object JVM creates an immutable instance of java.lang.Class which provides methods to examine the runtime properties of the object including its members and type information. Class also provides the ability to create new classes and objects.

With the exception of java.lang.reflect.ReflectPermission, none of the classes in java.lang.reflect have public constructors. To get to these classes, it is necessary to invoke appropriate methods on Class. So you can say that the entry point for all reflection operations is java.lang.Class.


How to get Class instance in Java

There are several ways to get a Class depending on whether the code has access to an object, the name of class, a type, or an existing Class.

Object.getClass()

If you have an instance of the class available, then you can get Class by invoking Object.getClass() method. This method will only work with reference types.

For Example– If you have a class called ClassA and an object objA of that class then you can get instance of Class as follows–

ClassA objA = new ClassA();
Class<?> cls = objA.getClass();

Using .class Syntax

If instance of the class is not available but the type is known, then you can get object of Class by using .class syntax. You just need to add “.class” to the name of the type. Using .class you can also get the Class for a primitive type.

For Example– If you want class object for type Boolean.

boolean b;
Class cls = boolean.class;

Note here that type (Boolean) is used to get instance of Class.

Same way if you want Class object for ClassA.

ClassA objA;
Class<?> cls1 = ClassA.class;

Then if you want to instantiate class object objA you can do that using class.newInstance() method.

try {
 objA = (ClassA)cls1.newInstance();
 objA.setI(12);
 System.out.println("Value of i " + objA.getI());
} catch (InstantiationException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
} catch (IllegalAccessException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}

Using Class.forName()

You can also get the instance of the class using the static method Class.forName().Make sure that you pass the fully-qualified class name. Which means you will have to include package names too.

For example, if you want instance of Class for ClassA which is residing in package org.prgm then do it as follows–

Class<?> c = Class.forName("org.prgm.ClassA");

Using TYPE Field for Primitive Type Wrappers

Wrapper classes for the primitive types have a field named TYPE which is equal to the Class for the primitive type being wrapped.

Class cls1 = Integer.TYPE;

Methods provided by class java.lang.Class

There are many methods provided by the class java.lang.Class to get the metadata about the class. Let’s go through an example to see some of these methods in practice.

Getting class information in Java using reflection

As a preparation for the example code let’s have a class called Parent.java which will be extended by the class ChildClass.java which is the class we are going to examine. There is also an interface IntTest.java which is implemented by ChildClass.java.

Parent class

public class Parent {
 String name;
 Parent(String name){
  this.name = name;
 }

 public void displayName(){
  System.out.println("Hello - " + name);
 }
 
 public String getName(){
  return name;
 }
}

IntTest interface

public interface IntTest {
   public void showValue();
}

ChildClass.java

public class ChildClass extends Parent implements IntTest{
 private int value;
 //Constructor
 public ChildClass(String name, int value) {
  super(name);
  this.value = value;
 }

 @Override
 public void showValue() {
  System.out.println("Value - " + value);
  
 }
}

Based on these classes let us see some of the methods provided by class Class.

Getting class name using reflection

If you want to get the class name using the instance of the Class.

Class<?> c = Class.forName("org.prgm.ChildClass");
System.out.println("Class name " + c.getName());
System.out.println("Class name " + c.getSimpleName());

Output

Class name org.prgm.ChildClass
Class name ChildClass

As you can see using the method getName() gives you the fully qualified name whereas getSimpleName() method gives you only the class name.

Getting super class using reflection

getSuperClass() method can be used for getting Super class. Returns the Class representing the superclass of the entity 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.

Class<?> c = Class.forName("org.prgm.ChildClass");
System.out.println("Super Class name " + c.getSuperclass());

Output

Super Class name - class org.prgm.Parent

Getting implemented or extended interfaces using reflection

getInterfaces() method can be used for getting the interfaces. If the object on which you are calling this method represents a class, the return value is an array containing objects representing all interfaces implemented by the class. If this object represents an interface, the array contains objects representing all interfaces extended by the interface.

Class<?> c = Class.forName("org.prgm.ChildClass");
System.out.println("interfaces - " + Arrays.toString(c.getInterfaces()));

Output

interfaces - [interface org.prgm.IntTest]

Getting class modifier using reflection

You can get the class modifier by using the getModifiers() method. Returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface; they should be decoded using the methods of class Modifier.

Class<?> c = Class.forName("org.prgm.ChildClass");
   
int modifiers = c.getModifiers();
System.out.println("Modifier - " + Modifier.toString(modifiers));

Output

Modifier – public

Getting fields of the class using reflection

There are 4 methods for getting fields of the class. If you want Field object for any specific field then you can use getDeclaredField(String name) or getField(String name) method. To get information for all the fields of the class you can following two methods.

  • getFields()- Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.
  • getDeclaredFields()- Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes inherited fields.
Class<?> c = Class.forName("org.prgm.ChildClass");

// Getting fields of the class
Field[] allFields = c.getFields();
System.out.println("All Fields - " + Arrays.toString(allFields));

// Getting fields of the class
Field[] fields = c.getDeclaredFields();
System.out.println("Fields - " + Arrays.toString(fields));

Output

All Fields - []
Fields - [private int org.prgm.ChildClass.value]

Since ChildClass.java doesn’t have any accessible public field (inherited or its own) so no value is returned for getFields() method.

There is one private field in ChildClass.java, getDeclaredFields() method shows that field.

Refer Reflection in Java - Field to read in detail about reflection API for field.

Getting constructors of the class using reflection

There are four methods for getting the constructors of the class. If you want Constructor object for any specific constructor, then you can use getConstructor(Class<?>... parameterTypes) or getDeclaredConstructor(Class<?>... parameterTypes) method. To get all the constructors of the class you can use following two methods.

  • getDeclaredConstructors()- Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object. These are public, protected, default (package) access, and private constructors.
  • getConstructors()- Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.
Class<?> c = Class.forName("org.prgm.ChildClass");

Constructor<?>[] constructors = c.getConstructors();
System.out.println("Constructors - " + Arrays.toString(constructors));
   
Constructor<?>[] Decconstructors = c.getDeclaredConstructors();
System.out.println("Declared constructors - " + Arrays.toString(Decconstructors));

Output

Constructors - [public org.prgm.ChildClass(java.lang.String,int)]
Declared constructors - [public org.prgm.ChildClass(java.lang.String,int)]

Since class ChildClass has only one public constructor so both methods are returning the same array of Constructor objects.

Refer Reflection in Java - Constructor to read in detail about reflection API for constructor.

Getting methods of the class using reflection

There are four methods for getting the methods of the class. If you want Method object for any specific constructor, then you can use getMethod(String name, Class<?>... parameterTypes) or getDeclaredMethod(String name, Class<?>... parameterTypes) method. To get all the methods of the class you can use following two methods.

  • 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.
  • 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.
Class<?> c = Class.forName("org.prgm.ChildClass");

// Getting all methods (even inherited) of the class
Method[] methods = c.getMethods();
System.out.println("All Methods - " + Arrays.toString(methods));
   
// Getting methods of the class
methods = c.getDeclaredMethods();
System.out.println("Class Methods - " + Arrays.toString(methods));

Output

All Methods - [public void org.prgm.ChildClass.showValue(), public java.lang.String org.prgm.Parent.getName(), 
public void org.prgm.Parent.displayName(), 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()]

Class Methods - [public void org.prgm.ChildClass.showValue()]

Here you can see how getMethods() shows all the methods even inherited one.

Refer Reflection in Java - Method to read in detail about reflection API for method.

Getting annotations using reflection

You can use following two methods in the class Class to get information about the annotations.

  • getAnnotations()- Returns annotations that are present on this element. If there are no annotations present on this element, the return value is an array of length 0.
  • getDeclaredAnnotations()- Returns annotations that are directly present on this element. This method ignores inherited annotations. If there are no annotations directly present on this element, the return value is an array of length 0.
Class<?> c = Class.forName("org.prgm.ChildClass");
   
Annotation[] annotations = c.getAnnotations();
System.out.println("Annotations - " + Arrays.toString(annotations));
   
Annotation[] Decannotations = c.getDeclaredAnnotations();
System.out.println("Annotations - " + Arrays.toString(Decannotations));

Output

Annotations - []
Annotations - []

Since there are no annotations present on the class so array length is zero for both methods. Note that these methods can be used in the same way with the object of Method or Field class to get annotations present on a method or a field.

That's all for this topic Reflection in Java - Getting Class Information. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Reflection API Tutorial
  2. Reflection in Java - Getting Field Information
  3. Reflection in Java - Array
  4. Generating Getters And Setters Using Reflection in Java
  5. Java Nested Class And Inner Class

You may also like-

  1. Spliterator in Java
  2. Method Reference in Java
  3. Interface Default Methods in Java
  4. Type Erasure in Java Generics
  5. Java Multithreading Interview Questions And Answers
  6. instanceof Operator in Java
  7. Java split() Method - Splitting a String
  8. Spring JdbcTemplate Insert, Update And Delete Example

Thursday, December 23, 2021

Reflection in Java - Getting Field Information

Reflection in Java-class gives a good idea about how class is an entry point to all the Reflection APIs. Once you have Class object you can get information about members of the class fields, constructors, methods. In this post we'll see how to get information about class fields using Java reflection API.

Class fields have a type and a value, the java.lang.reflect.Field class provides methods for accessing type information, field’s modifier and setting and getting values of a field on a given object.


Member Interface in Java Reflection API

With in the Reflection hierarchy an interface java.lang.reflect.Member is defined which is implemented by java.lang.reflect.Field, java.lang.reflect.Method, and java.lang.reflect.Constructor. Thus Member is an interface that reflects identifying information about a single member (a field or a method) or a constructor.

How to get Field object using reflection

There are 4 methods for getting fields of the 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.
  • getFields()- Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.
  • getDeclaredField(String name)- Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.
  • getDeclaredFields()- Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.

So getFields() methods will only return object for public fields where as getDeclaredField() methods will return all the fields.

Getting field information using Java reflection example

In this example generic class ReflectField is used which has few fields with access modifier as public or private.

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

public class ReflectField<T> {
  public String name = "Test";
  private int i = 10;
  public List<Integer> numList;
  public T val;
     
  public static void main(String arg[]){
    try {
      Class<?> c = Class.forName("org.netjs.prog.ReflectField");
      try {
        Field f = c.getField("name");
        System.out.println("Name field " + f.getName());
      
        Field[] fields = c.getFields();
        System.out.println("All Fields - " + Arrays.toString(fields));
        
        fields = c.getDeclaredFields();      
        System.out.println("Declared Fields - " + Arrays.toString(fields));
      } catch (NoSuchFieldException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }    
    }catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Output

Name field name

All Fields - [public java.lang.String org.netjs.prog.ReflectField.name, public java.util.List org.netjs.prog.ReflectField.numList, 
public java.lang.Object org.netjs.prog.ReflectField.val]

Declared Fields - [public java.lang.String org.netjs.prog.ReflectField.name, private int org.netjs.prog.ReflectField.i, 
public java.util.List org.netjs.prog.ReflectField.numList, public java.lang.Object org.netjs.prog.ReflectField.val]

You can see here getFields() return array of all public fields in the class where as getDeclaredFields() return all the fields (field i is having access modifier as private).

Getting field type using reflection

If you want to know the types of fields in any class using Java reflection API you can do it using the methods getType() and getGenericType().

Class<?> c = Class.forName("org.netjs.prog.ReflectField");
fields = c.getDeclaredFields();
for(Field field : fields){
  System.out.println("Field name - " + field.getName() 
      + " has Field Type " + field.getType());
  System.out.println("Field name - " + field.getName() 
      + " has Generic Field Type " + field.getGenericType());
}

Output

Field name - name has Field Type class java.lang.String
Field name - name has Generic Field Type class java.lang.String
Field name - i has Field Type int
Field name - i has Generic Field Type int
Field name - numList has Field Type interface java.util.List
Field name - numList has Generic Field Type java.util.List<java.lang.Integer>
Field name - val has Field Type class java.lang.Object
Field name - val has Generic Field Type T

Here notice that the type for the field val is displayed as java.lang.Object because generics are implemented via type erasure which removes all information regarding generic types during compilation. Thus T is replaced by the upper bound of the type variable, in this case, java.lang.Object.

Getting field modifiers using reflection

You can get the field modifiers by using the getModifiers() method. This method returns the Java language modifiers for the field represented by this Field object, as an integer. The Modifier class should be used to decode the modifiers.

Class<?> c = Class.forName("org.netjs.prog.ReflectField");
fields = c.getDeclaredFields();
for(Field field : fields){     
    System.out.println("Field name - " + field.getName() + " has modifier " 
       + Modifier.toString(field.getModifiers()));
}

Output

Field name - name has modifier public
Field name - i has modifier private
Field name - numList has modifier public
Field name - val has modifier public

Getting and Setting Field Values using reflection

If you have an object of a class, using Java reflection API you can set the values of fields in that class. This is typically done only in special circumstances when setting the values in the usual way is not possible. Because such access usually violates the design intentions of the class, it should be used with the utmost discretion.

Given a public field name which is of type String here the new value is set to the field name.

public String name = "Test";
Class<?> c = Class.forName("org.netjs.prog.ReflectField");
ReflectField rf = new ReflectField();
Field f = c.getField("name");
// getting the field value
System.out.println("Value of field name " + f.get(rf));
// setting the new field value
f.set(rf, "New Value");
System.out.println("Value of field name " + rf.name);

Output

Value of field name Test
Value of field name New Value

That's all for this topic Reflection in Java - Getting Field Information. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Reflection API Tutorial
  2. Reflection in Java - Getting Class Information
  3. Invoking Getters And Setters Using Reflection in Java
  4. Java Object Cloning - clone() Method
  5. Serialization and Deserialization in Java

You may also like-

  1. Java Nested Class And Inner Class
  2. Serialization Proxy Pattern in Java
  3. How to Pass Command Line Arguments in Eclipse
  4. Try-With-Resources in Java With Examples
  5. Type Casting in Java With Conversion Examples
  6. Lambda Expressions in Java 8
  7. Optional Class in Java With Examples
  8. ConcurrentHashMap in Java With Examples

Tuesday, February 9, 2021

Invoke Method at Runtime Using Java Reflection API

In this post we’ll see how to invoke a method at runtime using Java reflection API. You can even call a private method using reflection.

How to get the method instance

In order to invoke a method first thing you need to do is to get an instance of the Method. Using the class object (instance of the class in which method is defined) you can invoke one of the following methods to get an instance of a single method or get all the methods of the class in an array.

  • getMethod(String name, Class<?>... parameterTypes)- Using getMethod() you can get a Method object for the specified public member method of the class (instance or static). As method arguments pass the method name and the type of the method parameters.
  • getMethods()- This method returns an array containing Method objects for all the public methods of the class even the inherited ones.
  • getDeclaredMethod(String name, Class<?>... parameterTypes)- Using getDeclaredMethod() you can get a Method object for the specified method of the class (having any access modifier public, private, protected, default).
  • getDeclaredMethods()- This method returns an array containing Method objects for all the declared methods of the class including public, protected, default (package) access, and private methods, but excluding inherited methods.