Java का Reflection API
In this page:
Class<?> clazz = ClassName.class;
Method method = clazz.getMethod("methodName", parameterTypes);
method.invoke(object, arguments);
Accessing Class Objects
Reflection आपको runtime पर किसी class की विशेषताओं को inspect करने देता है -- इसके fields, superclass references, interfaces, और constructor metadata -- उन classes के लिए भी जिन्हें आपका code compile time पर नहीं जानता था, जो Spring और Hibernate जैसे frameworks को पीछे से शक्ति देता है।
उदाहरण: Accessing Class Objects
// Define the class Main
public class Main {
// Define the class Sample
static class Sample { int x; }
// Program entry point: the JVM starts running here
public static void main(String[] args) {
Class<?> clazz = Sample.class;
// Print a line to the console
System.out.println(clazz.getName() + " fields: " + clazz.getDeclaredFields().length);
}
}
Login to try C/C++/Java/PHP code in the editor
Accessing and Modifying Private Fields
Reflection का उपयोग करके, आप किसी field के सामान्य access controls को (setAccessible(true) के ज़रिए) bypass करके class के बाहर से private variables को inspect या override कर सकते हैं। यह शक्तिशाली है लेकिन frameworks और tests के बाहर इसका बहुत कम उपयोग होना चाहिए, क्योंकि यह class author के इरादे वाली encapsulation को तोड़ देता है।
उदाहरण: Accessing and Modifying Private Fields
import java.lang.reflect.Field;
public class Main {
static class Secret { private int value = 42; }
public static void main(String[] args) throws Exception {
Secret s = new Secret();
Field field = Secret.class.getDeclaredField("value");
field.setAccessible(true); // bypasses normal access control
System.out.println(field.getInt(s));
field.setInt(s, 100);
System.out.println(field.getInt(s));
}
}
Login to try C/C++/Java/PHP code in the editor
Calling Methods Dynamically
आप methods को उनके string name से dynamically ढूंढ और invoke कर सकते हैं, target object और runtime arguments को Method.invoke() में पास करते हुए, जो वह तरीका है जिससे frameworks compile time पर आपके annotated methods का exact signature जाने बिना उन्हें call करते हैं।
उदाहरण: Calling Methods Dynamically
import java.lang.reflect.Method;
public class Main {
static class Greeter { String greet(String name) { return "Hello, " + name; } }
public static void main(String[] args) throws Exception {
Method method = Greeter.class.getMethod("greet", String.class);
Object result = method.invoke(new Greeter(), "Riya"); // looked up by name, called dynamically
System.out.println(result);
}
}
Login to try C/C++/Java/PHP code in the editor
Instantiating Classes Dynamically
Constructor reflection आपको अपने code में कभी भी explicit 'new ClassName()' लिखे बिना runtime पर objects instantiate करने देता है, एक Constructor object ढूंढकर और newInstance() call करके -- उन frameworks के लिए ज़रूरी जो hardcoded types के बजाय configuration या annotations के आधार पर objects बनाते हैं।
उदाहरण: Instantiating Classes Dynamically
import java.lang.reflect.Constructor;
public class Main {
static class Point { int x; Point(int x) { this.x = x; } }
public static void main(String[] args) throws Exception {
Constructor<Point> ctor = Point.class.getConstructor(int.class);
Point p = ctor.newInstance(5); // no explicit "new Point(5)" in this code
System.out.println(p.x);
}
}
Login to try C/C++/Java/PHP code in the editor
Performance Impact of Reflection
Reflective calls direct method calls को मिलने वाले कई JIT compiler optimizations को bypass कर देती हैं, इसलिए वे साधारण programmatic calls से measurably धीमी चलती हैं। यह आमतौर पर एक-बार की framework setup के काम के लिए ठीक है, लेकिन performance-critical hot loops के अंदर इससे बचना चाहिए।
उदाहरण: Performance Impact of Reflection
import java.lang.reflect.Method;
public class Main {
static int square(int n) { return n * n; }
public static void main(String[] args) throws Exception {
Method method = Main.class.getDeclaredMethod("square", int.class);
long start = System.nanoTime();
for (int i = 0; i < 1000; i++) method.invoke(null, i); // measurably slower than a direct call
System.out.println("Reflective calls took " + (System.nanoTime() - start) + "ns");
}
}
Login to try C/C++/Java/PHP code in the editor
- किसी private method के लिए
getMethodका उपयोग करना, जोNoSuchMethodExceptionफेंकता है क्योंकि यह सिर्फ public वाले ढूंढता है;getDeclaredMethodऔरsetAccessible(true)का उपयोग करें। - गलत argument types या count के साथ
method.invoke(obj, ...)call करना, जोIllegalArgumentExceptionफेंकता है। - वहां reflection का उपयोग करना जहां एक normal method call काम कर जाती, जो धीमा है और errors को compile time से runtime में ले जाता है।
Chapter Quiz — Complete all 19 topics to unlock
0/19 topics done
Complete these topics first:
- Java Reflection API
- Java Annotations Advanced
- Java Garbage Collection
- Java Memory Management
- Java Performance Optimization
- Java Advanced Interview Questions
- Java CompletableFuture
- Java Atomic Classes
- Java Locks & Semaphores
- Java Concurrent Collections
- Java Cryptography Basics
- Java Hashing (MD5, SHA)
- Java SSL & HTTPS
- Java Logging (Log4j/SLF4J)
- Java Serialization Advanced
- Java Interview Questions Advanced
- Java Connection Pooling
- Java Test Driven Development
- Java Integration Testing