Call Methods at Runtime Using Java Reflection
Last updated
Was this helpful?
Last updated
Was this helpful?
Fuente:
Invocar metodos de la clase o una superclase
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.
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);
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);