Java Reflection API with Example

Safalta Expert Published by: Vanshika Jakhar Updated Fri, 27 Sep 2024 06:46 PM IST

In this article, we'll talk about Java reflection. Here, we'll examine what Java Reflection is and how it works to obtain data. We will also consider the advantages and disadvantages of Java's reflection. In addition, we will comprehend a Java reflection class and some sample code that uses reflection. Invoking a method using Java reflection will allow us to see the Java reflection in action.

Download these FREE Ebooks:
1. Introduction to Digital Marketing
2. Website Planning and Creation

Table of Content
What does "Java reflection" mean?
How Does Java Reflection Collect Data?
Class in java. lang. reflect Package
Java. lang.methods Class's
Java Reflection's advantages and disadvantages
Examples of Java Reflections
 

What does "Java reflection" mean?

Application Programming Interface (API) reflection in Java is used at runtime to change classes, methods, and interfaces. It is also used to examine or modify the behavior of methods, classes, and interfaces while they are in use. Reflection provides information about the class that an object belongs to as well as the methods for that class that use the object in their execution. Reflection allows us to invoke methods at runtime regardless of the access specifiers used with them.

Free Demo Classes

Register here for Free Demo Classes


 

How Does Java Reflection Collect Data?

Reflection can be used to obtain information about -

Class: To find the name of the class that an object belongs to, use the getClass() method.

Constructors: The public constructors of the class that an object belongs to can be obtained using the getConstructors() method.

Strategies: The public methods for the class that an object belongs to can be obtained using the getMethods() method.

You can check other related blogs below:
1. Powerful SEO Techniques to rank in Google
2. How to get powerful SEO backlinks? Top 10 Tips to get Backlinks

3. Search Intent - All You Should know
4. What is page experience in Digital marketing?

5. SEO Vs PPC: Which is beneficial?
6. 7 Tips for combine Website Content to Improve SEO
7. 6 Reasons Email Marketing increase holiday sales
8. 6 SEO hacks to revive your Website

 

Class in java. lang. reflect Package

The list of different Java classes in the java.lang.package to implement reflection is as follows:

Field: This class is used to collect declarative data, such as a variable's name, value, datatype, and access modifier.

Method: This class is used to collect declarative information about a method, including its name, return type, access modifier, parameter types, and exception type.

Constructor: This class is used to collect declarative information about a constructor, such as a name, access modifier, and parameter types.

Modifier: To learn more about a specific access modifier, use this class.
 

Java. lang.methods Class's

  • The class name is returned by the public-str getName function.
  • The superclass reference is returned by the public method getSuperclass().
  • Private Class, An array of interfaces implemented by the specified class is returned by the getInterfaces() method.
  • Public static String to String (int I method), which returns the access specifier for the specified class, requires a parameter called "public static String to String ()" to be passed as it returns an integer value representing the modifiers of the specified class.

 

Java Reflection's advantages and disadvantages

Advantages of Java Reflection- 

  • Extensibility Features: An application can use outer, user-defined classes by creating extensibility objects using examples of those classes' fully qualified names.
  • Device debugging and testing: Debuggers use the reflection property to look at individual students in classes.
 

Disadvantages of Java's Reflection-

  • Execution Time: Reflective tasks take longer to complete.
  • Internals: Reflective code disrupts thought processes.

 

Examples of JAVA Reflection 

Example -1 : Accessing Class Information

Class clazz = String.class;
System.out.println("Class Name: " + clazz.getName());

Output 
Class Name: java.lang.String

Example 2: Accessing Methods

Method[] methods = String.class.getMethods();
for (Method method : methods) {
 System.out.println("Method: " + method.getName());
}

Example 3: Invoking Methods

try {
    Method method = String.class.getMethod("substring", int.class, int.class);
    String str = "Reflection in Java";
    String result = (String) method.invoke(str, 11, 15);
    System.out.println(result);
} catch (Exception e) {
    e.printStackTrace();
}

Output
Java

Example 4: Accessing Private Fields
try {
    Class clazz = MyClass.class;
    Field field = clazz.getDeclaredField("privateField");
    field.setAccessible(true);  // Bypass private modifier
    MyClass obj = new MyClass();
    field.set(obj, "new value");
    System.out.println("Updated Field: " + field.get(obj));
} catch (Exception e) {
    e.printStackTrace();
}


 

Consequently, we have a thorough understanding of Java reflection. In addition, we covered an introduction to reflection in Java in this tutorial. Along with this, Java Reflection's benefits and drawbacks were demonstrated. Finally, with the aid of examples, we learned about the Java reflection class and how Java reflection invokes a method.

What is accurate regarding Java reflection and API?

Java Reflection is a process for looking at or changing a class's run-time behavior. A class's run-time behavior can be examined and changed using a variety of methods provided by java. lang. Class class.

Is Java reflection effective in terms of speed?

Reflective operations, as a result of their slower performance compared to their non-reflective counterparts, should be avoided in code segments that are frequently called in performance-sensitive applications.

Why reflection is expensive?

Reflection needs to load and then process a significant amount of the type metadata. As a result, there may be more memory overhead and slower processing.

Related Article

CTET Answer Key 2024: दिसंबर सत्र की सीटेट परीक्षा की उत्तर कुंजी जल्द होगी जारी, जानें कैसे कर सकेंगे डाउनलोड

Read More

CLAT 2025: दिल्ली उच्च न्यायालय ने एनएलयू को दिया क्लैट परीक्षा के नतीजों में संशोधन का आदेश, जानें पूरा मामला

Read More

UP Police: यूपी पुलिस भर्ती का आवेदन पत्र डाउनलोड करने का एक और मौका, यूपीपीआरपीबी ने फिर से सक्रिया किया लिंक

Read More

JEE Advanced 2025: जेईई एडवांस्ड के लिए 23 अप्रैल से शुरू होगा आवेदन, जानें कौन कर सकता है पंजीकरण

Read More

UPSC CSE Mains 2024 Interview Schedule out now; Personality tests from 7 January, Check full timetable here

Read More

Common Admission Test (CAT) 2024 Result out; 14 Students Score 100 Percentile, Read here

Read More

CAT Result: कैट परीक्षा के परिणाम जारी, इतने उम्मीदवारों ने 100 पर्सेंटाइल स्कोर किए हासिल; चेक करें रिजल्ट

Read More

CBSE: डमी प्रवेश रोकने के लिए सीबीएसई का सख्त कदम, 18 स्कूलों को जारी किया कारण बताओ नोटिस

Read More

Jharkhand Board Exam Dates 2025 released; Exams from 11 February, Check the full schedule here

Read More