RKTechGame | Java Reflection API Explained

Java Reflection API kya hai?

Reflection API Java me ek powerful feature hai jo runtime par classes, methods, fields, aur constructors ke baare me information prapt karne aur unhe manipulate karne deta hai.

Matlab program chalne ke dauraan bhi hum code ke structure ko samajh sakte hain, new objects bana sakte hain, methods call kar sakte hain bina compile time knowledge ke.

Reflection API ke Important Classes

Basic Reflection Example

import java.lang.reflect.Method;

public class ReflectionDemo {
    public static void main(String[] args) throws Exception {
        // Class object prapt karna
        Class<String> cls = String.class;

        // Class ke methods ko prapt karna
        Method[] methods = cls.getDeclaredMethods();

        // Methods ke name print karna
        for (Method method : methods) {
            System.out.println("Method Name: " + method.getName());
        }
    }
}

Is example me humne String class ke methods ko runtime par list kiya hai.

Private Fields aur Methods Access Karna

Reflection se hum private fields ya methods ko bhi access kar sakte hain:

import java.lang.reflect.Field;

public class PrivateFieldAccess {
    private String secret = "Hidden";

    public static void main(String[] args) throws Exception {
        PrivateFieldAccess obj = new PrivateFieldAccess();

        // Class object
        Class<?> cls = obj.getClass();

        // Private field prapt karna
        Field field = cls.getDeclaredField("secret");

        // Field accessible banana
        field.setAccessible(true);

        // Field value lena
        String value = (String) field.get(obj);
        System.out.println("Secret Value: " + value);
    }
}

Methods Invoke Karna Reflection se

import java.lang.reflect.Method;

public class MethodInvokeExample {
    public void hello(String name) {
        System.out.println("Hello, " + name);
    }

    public static void main(String[] args) throws Exception {
        MethodInvokeExample obj = new MethodInvokeExample();

        // Class object
        Class<?> cls = obj.getClass();

        // Method prapt karna
        Method method = cls.getDeclaredMethod("hello", String.class);

        // Method invoke karna
        method.invoke(obj, "RKTechGame");
    }
}