Java Annotations
Java Annotations का सिंटैक्स सरल है: यह '@' चिन्ह से शुरू होती है और इसे क्लास, मेथड, फील्ड या पैकेज के साथ लागू किया जा सकता है। Advanced डेवलपमेंट में, आप custom annotations बनाकर उन्हें reflection और proxy patterns के साथ जोड़ सकते हैं। यह ऑब्जेक्ट-ओरिएंटेड प्रिंसिपल्स जैसे inheritance, encapsulation, और polymorphism के साथ seamless integration सुनिश्चित करता है।
इस ट्यूटोरियल में आप सीखेंगे कि कैसे Java में built-in और custom annotations बनाते हैं, उनका उपयोग करते हैं और उन्हें real-world applications में implement करते हैं। हम practical examples और hands-on code snippets के माध्यम से syntax, data structures, और algorithms के साथ advanced design patterns भी कवर करेंगे। इसके अलावा, common pitfalls जैसे memory leaks, poor error handling, और inefficient algorithms से बचने के लिए best practices का ध्यान रखा जाएगा।
मूल उदाहरण
javaimport java.lang.annotation.*;
import java.lang.reflect.*;
// Custom Annotation बनाना
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface RunMe {
String value() default "Default Task";
}
// Annotation का उपयोग करना
class TaskRunner {
@RunMe(value = "Cleanup Task")
public void cleanup() {
System.out.println("Running cleanup task");
}
@RunMe
public void defaultTask() {
System.out.println("Running default task");
}
}
public class AnnotationDemo {
public static void main(String\[] args) throws Exception {
TaskRunner runner = new TaskRunner();
Method\[] methods = TaskRunner.class.getDeclaredMethods();
for(Method method : methods) {
if(method.isAnnotationPresent(RunMe.class)) {
RunMe annotation = method.getAnnotation(RunMe.class);
System.out.println("Executing: " + annotation.value());
method.invoke(runner);
}
}
}
}
उपर्युक्त कोड में हमने एक custom annotation @RunMe
बनाया, जिसे method level पर लागू किया गया है। @Retention(RetentionPolicy.RUNTIME)
यह सुनिश्चित करता है कि annotation रन-टाइम पर उपलब्ध हो और reflection के जरिए access किया जा सके। @Target(ElementType.METHOD)
यह तय करता है कि यह annotation केवल methods पर ही लागू हो सकता है।
TaskRunner
क्लास में दो methods हैं, जिनमें @RunMe
annotation लागू है। पहला method cleanup
custom value के साथ annotation को दर्शाता है, जबकि defaultTask
default value का उपयोग करता है। मुख्य method main
reflection का उपयोग कर class के सभी methods को iterate करता है, और जो methods @RunMe
annotation के साथ मार्केड हैं, उन्हें invoke करता है।
यह example practical applications को दिखाता है जैसे task scheduling, automated testing या runtime configuration management। Advanced developers इसे dynamically task execution, logging, या custom framework behavior implement करने के लिए extend कर सकते हैं। ध्यान दें कि reflection के उपयोग से performance impact हो सकता है, इसलिए इसे सही context में ही लागू करना चाहिए।
व्यावहारिक उदाहरण
javaimport java.lang.annotation.*;
import java.lang.reflect.*;
import java.util.*;
// Advanced Custom Annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface ScheduledTask {
int interval() default 1; // interval in seconds
}
class Scheduler {
@ScheduledTask(interval = 5)
public void reportGeneration() {
System.out.println("Generating report at " + new Date());
}
@ScheduledTask(interval = 2)
public void dataCleanup() {
System.out.println("Cleaning data at " + new Date());
}
}
public class AdvancedAnnotationDemo {
public static void main(String\[] args) throws Exception {
Scheduler scheduler = new Scheduler();
Method\[] methods = Scheduler.class.getDeclaredMethods();
Timer timer = new Timer();
for(Method method : methods) {
if(method.isAnnotationPresent(ScheduledTask.class)) {
ScheduledTask task = method.getAnnotation(ScheduledTask.class);
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
try {
method.invoke(scheduler);
} catch(Exception e) {
e.printStackTrace();
}
}
}, 0, task.interval() * 1000);
}
}
}
}
इस advanced example में हमने @ScheduledTask
annotation का उपयोग करके एक real-world scheduler system implement किया। प्रत्येक annotated method अलग-अलग intervals पर execute होता है, जो कि practical backend applications जैसे reporting, cleanup, या batch processing के लिए उपयुक्त है।
Timer और TimerTask का उपयोग करके हम asynchronous execution और scheduling achieve कर सकते हैं। Reflection method.invoke के साथ, annotation runtime behavior को dynamically control करने में मदद करता है। Best practices के अनुसार, exception handling implemented है ताकि runtime errors को safely handle किया जा सके। Memory leaks से बचने के लिए Timer और TimerTask के resources को properly manage करना आवश्यक है।
यह उदाहरण algorithms (timed execution) और OOP principles (encapsulation of tasks within Scheduler class) को स्पष्ट रूप से दर्शाता है। इसे enterprise-level backend systems में dynamic task management, automated workflows और framework integration के लिए इस्तेमाल किया जा सकता है।
Java Annotations के लिए best practices और common pitfalls:
- Best Practices:
* हमेशा@Retention
और@Target
specify करें ताकि annotations predictable और maintainable हों।
* Reflection का उपयोग सोच-समझ कर करें, क्योंकि यह performance को प्रभावित कर सकता है।
* Custom annotations में default values प्रदान करें, जिससे flexibility बढ़ती है।
* Exception handling और logging का ध्यान रखें, खासकर runtime execution में। - Common Pitfalls:
* Unnecessary reflection या overuse annotations memory overhead बढ़ा सकता है।
* Poor error handling, जैसेmethod.invoke
में unchecked exceptions, runtime failures का कारण बन सकते हैं।
* Inefficient algorithms, जैसे tight loops में reflection calls, performance degrade कर सकते हैं।
* Security vulnerabilities, जैसे sensitive methods पर unrestricted invocation, ध्यान में रखें। - Debugging Tips:
* Reflection calls पर breakpoints और logging लगाएँ।
* Annotation values को validate करने के लिए unit tests बनाएं।
* Timer और scheduled tasks के लिए proper shutdown hooks implement करें। - Performance Optimization:
* Frequently used reflection results को cache करें।
* Lightweight annotations बनाएं और unnecessary runtime retention से बचें।
* Memory-intensive operations को asynchronous या batched तरीके से execute करें।
📊 संदर्भ तालिका
Element/Concept | Description | Usage Example |
---|---|---|
@Retention | Determines how long annotation is retained (SOURCE, CLASS, RUNTIME) | @Retention(RetentionPolicy.RUNTIME) |
@Target | Specifies where annotation can be applied (CLASS, METHOD, FIELD, etc.) | @Target(ElementType.METHOD) |
@Inherited | Allows subclass to inherit annotation from superclass | @Inherited |
@Deprecated | Marks method or class as deprecated | @Deprecated |
@Override | Indicates method overrides superclass method | @Override |
@SuppressWarnings | Suppress compiler warnings for a specific scope | @SuppressWarnings("unchecked") |
आगे बढ़ने के लिए, developers custom annotations के साथ reflection, proxy patterns, और AOP (Aspect-Oriented Programming) को समझ सकते हैं। Recommended next topics: Spring Framework annotations, Java EE annotations, और annotation processors। Practical advice: हमेशा performance, security, और maintainability का ध्यान रखते हुए annotations implement करें। Learning resources में official Java documentation, tutorials, और open-source frameworks के source code शामिल हैं।
🧠 अपने ज्ञान की परीक्षा करें
अपना ज्ञान परखें
व्यावहारिक प्रश्नों के साथ इस विषय की अपनी समझ का परीक्षण करें।
📝 निर्देश
- हर प्रश्न को ध्यान से पढ़ें
- हर प्रश्न के लिए सबसे अच्छा उत्तर चुनें
- आप जितनी बार चाहें क्विज़ दोबारा दे सकते हैं
- आपकी प्रगति शीर्ष पर दिखाई जाएगी