- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I invoke a Java method when given the method name as a string?
The java.lang.reflect.Method class provides information about, and access to, a single method on a class or interface. The reflected method may be a class method or an instance method (including an abstract method). A Method permits widening conversions to occur when matching the actual parameters to invoke with the underlying method's formal parameters, but it throws an IllegalArgumentException if a narrowing conversion would occur.
You can invoke the method using the class named method of the package java.lang.reflect. The constructor of this class accepts the method name in the form of a string. And you can invoke this method using the invoke() method.
Example
import java.lang.reflect.Method; public class DemoTest { private void sampleMethod(){ System.out.println("hello"); } } public class SampleTest { public static void main(String args[]) throws Exception{ Class c = Class.forName("DemoTest"); Object obj = c.newInstance(); Method method = c.getDeclaredMethod("sampleMethod", null); method.setAccessible(true); method.invoke(obj, null); } }
- Related Articles
- How to invoke a JavaScript Function as a method?
- How can we invoke the parent's method, when a child has a method with the same name in JavaScript?
- How to invoke a function as a function and method?
- How do I time a method execution in Java
- How to execute a JavaScript function when I have its name as a string?
- How do I write method names in Java?
- Can we define a method name same as class name in Java?
- How does TestNG invoke a test method using multiple threads?
- How do we call a Java method recursively?
- Can a method have the same name as the class?
- When overriding clone method, why do we need to declare it as public in Java?
- How do I determine if a String contains another String in Java?
- How do I create a Java string from the contents of a file?
- How do I discover the Quarter of a given Date in Java?
- How to invoke a JavaScript Function as a function?

Advertisements