Sobes.tech
Middle

What is reflexivity?

sobes.tech AI

Answer from AI

Reflection in Java is a mechanism that allows exploring and manipulating objects, classes, interfaces, and methods at runtime.

Main capabilities:

  • Obtaining information about classes and their members (fields, methods, constructors) during runtime.
  • Creating instances of classes even if the class name is unknown before runtime.
  • Calling methods of objects with unknown method names.
  • Accessing and modifying object fields, even if they are private.

Applications:

  • Frameworks (e.g., Spring, Hibernate) actively use reflection for dependency injection, ORM, etc.
  • Testing tools.
  • Serialization and deserialization of objects.

Example of obtaining class information:

// Getting a Class object
Class<?> myClass = String.class;

// Getting the class name
String className = myClass.getName();

// Getting all public methods
java.lang.reflect.Method[] methods = myClass.getMethods();

// Getting all declared fields (including private)
java.lang.reflect.Field[] fields = myClass.getDeclaredFields();

Example of creating a class instance and calling a method:

try {
    // Getting a Class object by name
    Class<?> myClass = Class.forName("java.lang.String");

    // Creating a new instance of the class
    Object instance = myClass.getDeclaredConstructor().newInstance();

    // Getting a method by name and parameter type
    java.lang.reflect.Method method = myClass.getMethod("length");

    // Invoking the method on the created instance
    Object result = method.invoke(instance);

    System.out.println("String length: " + result); // Will output 0 for an empty string

} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | java.lang.reflect.InvocationTargetException e) {
    e.printStackTrace();
}

Disadvantages:

  • Performance: Reflection is slower than direct member access.
  • Security: Reflection can break encapsulation by allowing access to private members.
  • Lack of compile-time type checking: Some type-related errors can only be detected at runtime.
  • Maintenance complexity: Code using reflection can be less readable and harder to maintain.
What is reflexivity? — Java - sobes.tech