CKTIS / Java
Reflexão em Java
Reflexão em Java: A reflexão expõe metadados runtime e construção, acesso a campos e invocação dinâmicos através de Class, Method, Field e Constructor.
Versão: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Sintaxe
reflectionA reflexão expõe metadados runtime e construção, acesso a campos e invocação dinâmicos através de Class, Method, Field e Constructor.
Usa-a em infraestrutura de plugins, serialização ou DI, limita o âmbito e mantém em cache metadados já validados.
As verificações de acesso e JPMS continuam ativas; trySetAccessible pode devolver false e acesso forçado causar InaccessibleObjectException.
Um método ausente lança NoSuchMethodException; Method.invoke embrulha a exceção alvo em InvocationTargetException e erasure pode criar métodos bridge.
getDeclaredMethod encontra greet(String) privado: stdout começa por greet String; trySetAccessible devolve true e invoke escreve Hello, Ada.
Exemplos
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 encontra greet(String) privado: stdout começa por greet String; trySetAccessible devolve true e invoke escreve Hello, Ada.