java
  • Introduction
  • Patrones de Diseño
    • Builder Design Pattern
  • Java 8
    • Ordenar List
    • Optional
    • Gradle
    • filter
    • Lambda y Stream
  • Java 9
  • Java 10
  • Java 11
  • Java 12
  • Performance
  • Modularidad
  • GraalVM
    • Graalvm
  • JUnit
  • Apache Archiva
    • Apache Archiva
  • Dropbox APi
  • JVM Configuracion
    • JVM Configuration
    • NetBeans.conf
    • Glassfish
  • Data Science in Pure Java
  • Reflection
    • Call Methods at Runtime Using Java Reflection
  • LambdaMetaFactory
Powered by GitBook
On this page
  • Obtaining aMethodObject
  • 3.1.getMethod()
  • 3.2.getDeclaredMethod()

Was this helpful?

  1. Reflection

Call Methods at Runtime Using Java Reflection

PreviousReflectionNextLambdaMetaFactory

Last updated 6 years ago

Was this helpful?

Fuente:

Invocar metodos de la clase o una superclase

Obtaining aMethodObject

First, we need to get a_Method_object that reflects the method we want to invoke. The_Class_object, representing the type in which the method is defined, provides two ways of doing this.

3.1.getMethod()

We can use_getMethod()_to find any public method, be it static or instance that is defined in the class or any of its superclasses.

It receives the method name as the first argument, followed by the types of the method’s arguments:

123456

Method sumInstanceMethod= Operations.class.getMethod("publicSum",int.class,double.class);Method multiplyStaticMethod= Operations.class.getMethod("publicStaticMultiply",float.class,long.class);

3.2.getDeclaredMethod()

We can use_getDeclaredMethod()_to get any method defined in the class. This includes public, protected, default access, and even private methods but excludes inherited ones.

It receives the same parameters asgetMethod():

123

Method andPrivateMethod= Operations.class.getDeclaredMethod("privateAnd",boolean.class,boolean.class);

12

Method maxProtectedMethod= Operations.class.getDeclaredMethod("protectedMax",int.class,int.class);

https://www.baeldung.com/java-method-reflection