# Call Methods at Runtime Using Java Reflection

Fuente:

[https://www.baeldung.com/java-method-reflection](https://www.baeldung.com/java-method-reflection)

Invocar metodos de la clase o una superclase

```java
```

## **Obtaining a**_**Method**_**Object**

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 a&#x73;_&#x67;etMethod()_:

| 123 | `Method andPrivateMethod= Operations.class.getDeclaredMethod("privateAnd",boolean.class,boolean.class);` |
| --- | -------------------------------------------------------------------------------------------------------- |

| 12 | `Method maxProtectedMethod= Operations.class.getDeclaredMethod("protectedMax",int.class,int.class);` |
| -- | ---------------------------------------------------------------------------------------------------- |
