CKTIS / Java
Reflexión en Java
Reflexión en Java: La reflexión expone metadatos runtime y construcción, acceso a campos e invocación dinámicos mediante Class, Method, Field y Constructor.
Versión: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Sintaxis
reflectionLa reflexión expone metadatos runtime y construcción, acceso a campos e invocación dinámicos mediante Class, Method, Field y Constructor.
Úsala en infraestructura de plugins, serialización o DI, limita su alcance y guarda en caché los metadatos ya validados.
Los controles de acceso y JPMS siguen vigentes; trySetAccessible puede devolver false y el acceso forzado causar InaccessibleObjectException.
Un método ausente lanza NoSuchMethodException; Method.invoke envuelve la excepción objetivo en InvocationTargetException y el erasure puede crear métodos bridge.
getDeclaredMethod encuentra greet(String) privado: stdout empieza con greet String; trySetAccessible devuelve true e invoke imprime Hello, Ada.
Ejemplos
import java.lang.reflect.Method;
public class Main {
private static class Greeter {
private String greet(String name) {
return "Hello, " + name;
}
}
public static void main(String[] args) throws Exception {
Method method = Greeter.class.getDeclaredMethod("greet", String.class);
System.out.println(method.getName() + " " + method.getParameterTypes()[0].getSimpleName());
System.out.println(method.trySetAccessible());
System.out.println(method.invoke(new Greeter(), "Ada"));
}
}
Resultado
greet String true Hello, Ada
getDeclaredMethod encuentra greet(String) privado: stdout empieza con greet String; trySetAccessible devuelve true e invoke imprime Hello, Ada.