← Back to Advanced Java Course | Chapter 11: Advanced & Security | Lesson 1 of 19

Java का Reflection API

Reflection किसी program को चलते समय अपनी खुद की classes को देखने और उपयोग करने देता है, जैसे अपने ही toolbox के labels पढ़ना। आप methods ढूंढ सकते हैं और उन्हें नाम से call भी कर सकते हैं।
Syntax
java
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

java
// 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);
	}
}

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

java
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));
	}
}

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

java
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);
	}
}

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

java
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);
	}
}

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

java
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");
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी private method के लिए getMethod का उपयोग करना, जो NoSuchMethodException फेंकता है क्योंकि यह सिर्फ public वाले ढूंढता है; getDeclaredMethod और setAccessible(true) का उपयोग करें।
  2. गलत argument types या count के साथ method.invoke(obj, ...) call करना, जो IllegalArgumentException फेंकता है।
  3. वहां reflection का उपयोग करना जहां एक normal method call काम कर जाती, जो धीमा है और errors को compile time से runtime में ले जाता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.