Java — Reflection in Java | Code Factory

  • Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.
  • Class: The getClass() method is used to get the name of the class to which an object belongs.
  • Constructors: The getConstructors() method is used to get the public constructors of the class to which an object belongs.
  • Methods: The getMethods() method is used to get the public methods of the class to which an objects belongs.
package com.example.java.programming;/* A simple Java program to demonstrate the use of reflection */
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* @author code.factory
*/
/* class whose object is to be created */
class Demo {

/* creating a private field */
private String s;

/* creating a public constructor */
public Demo() {
s = "Code Factory";
}

/* creating a public method with no arguments */
public void method1() {
System.out.println("The string is: " + s);
}

/* creating a public method with int as argument */
public void method2(int n) {
System.out.println("The number is: " + n);
}

/* creating a private method */
private void method3() {
System.out.println("Private method invoked");
}
}
public class Test {
public static void main(String... strings) throws Exception {

/* creating object whose property is to be checked */
Demo demo = new Demo();

/* creating class object from the object using getClass() method */
Class cls = demo.getClass();
System.out.println("The name of class is: " + cls.getName());

/* getting the constructor of the class through the object of the class */
Constructor constructor = cls.getConstructor();
System.out.println("The name of constructor is: " + constructor.getName());

System.out.println("The public methods of class are:");

/* getting methods of the class through the object
* of the class by using getMethods() */
Method[] methods = cls.getMethods();

for(Method method : methods) {
System.out.println(" - " + method.getName());
}

/* creates object of desired method by providing the
* method name and parameter class as arguments to
* the getDeclaredMethod() */
Method methodCall1 = cls.getDeclaredMethod("method2", int.class);

/* invokes the method at runtime */
methodCall1.invoke(demo, 34);

/* creates object of the desired field by providing
* the name of field as argument to the
* getDeclaredField() method */
Field field = cls.getDeclaredField("s");

/* allows the object to access the field irrespective
* of the access specifier used with the field */
field.setAccessible(true);

/* takes object and the new value to be assigned
* to the field as arguments */
field.set(demo, "CODE");

/* Creates object of desired method by providing the
* method name as argument to the getDeclaredMethod() */
Method methodCall2 = cls.getDeclaredMethod("method1");

/* invokes the method at runtime */
methodCall2.invoke(demo);

/* Creates object of the desired method by providing
* the name of method as argument to the
* getDeclaredMethod() method */
Method methodCall3 = cls.getDeclaredMethod("method3");

/* allows the object to access the method irrespective
* of the access specifier used with the method */
methodCall3.setAccessible(true);

/* invokes the method at runtime */
methodCall3.invoke(demo);
}
}
The name of class is: com.example.java.programming.Demo
The name of constructor is: com.example.java.programming.Demo
The public methods of class are:
- method2
- method1
- wait
- wait
- wait
- equals
- toString
- hashCode
- getClass
- notify
- notifyAll
The number is: 34
The string is: CODE
Private method invoked

Uses of Reflection

  • Extensibility Features: An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.
  • Class Browsers and Visual Development Environments: A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.
  • Debuggers and Test Tools: Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.

Drawbacks of Reflection

  • Performance Overhead: Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
  • Security Restrictions: Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.
  • Exposure of Internals: 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, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

MADNFT Weekly Update

How to create cross-AWS account RStudio connectivity with Amazon S3 & Redshift

Abstract Guilds of Craftsmen

Python — Descriptors and Properties

My Journey into Development

Common Feature Store Workflow with Feast

Structs and the in keyword in C#

A Practical Introduction to Kafka Storage Internals

Kafka

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

Visitor Design Pattern in Java

Deep dive into Pattern Matching for Java

Java Threads

Right Garbage Collector in Java simplified