Skip to content
Fix Code Error

How do I invoke a Java method when given the method name as a string?

March 13, 2021 by Code Error
Posted By: brass-kazoo

If I have two variables:

Object obj;
String methodName = "getName";

Without knowing the class of obj, how can I call the method identified by methodName on it?

The method being called has no parameters, and a String return value. It’s a getter for a Java bean.

Solution

Coding from the hip, it would be something like:

java.lang.reflect.Method method;
try {
  method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) { ... }
  catch (NoSuchMethodException e) { ... }

The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give methodName).

Then you invoke that method by calling

try {
  method.invoke(obj, arg1, arg2,...);
} catch (IllegalArgumentException e) { ... }
  catch (IllegalAccessException e) { ... }
  catch (InvocationTargetException e) { ... }

Again, leave out the arguments in .invoke, if you don’t have any. But yeah. Read about Java Reflection

Answered By: wolfie

Related Articles

  • How can I resolve Web Component Testing error?
  • Identifying and solving…
  • How to access parameters in a RESTful POST method
  • error LNK2005: ✘✘✘ already defined in…
  • How to write dynamic variable in Ansible playbook
  • JPA Hibernate Persistence exception…
  • LDAP root query syntax to search more than one specific OU
  • org.springframework.beans.factory.BeanCreationExcept…
  • Spring data jpa- No bean named…
  • Neither BindingResult nor plain target object for…
  • UnsatisfiedDependencyException: Error creating bean…
  • When I'm testing a web app by JUnit and Mockito I…
  • How to choose the right bean scope?
  • How to pass class instance and all it does to…
  • NullpointerException error while working with…
  • org.springframework.beans.factory.NoSuchBeanDefiniti…
  • Eclipse will not start and I haven't changed anything
  • Can't access Eclipse marketplace
  • java.lang.RuntimeException: Unable to instantiate…
  • TypeScript metadata reflection references other…
  • Cannot expand and concatenate GCC macros into one
  • AppCompat v7 r21 returning error in values.xml?
  • Unable to run Robolectric and Espresso with a…
  • Using enums in a spring entity
  • An Authentication object was not found in the…
  • Spring Boot with ElasticSearch in Groovy: WebClient…
  • Get JSF managed bean by name in any Servlet related class
  • How to populate options of h:selectOneMenu from database?
  • Form field border-radius is not working only on the…
  • Configure hibernate to connect to database via JNDI…
  • "Non-resolvable parent POM: Could not transfer…
  • Differences between action and actionListener
  • Android + Pair devices via bluetooth programmatically
  • ClassNotFoundException:…
  • How to parse JSON file with Spring
  • Injection of autowired dependencies failed;
  • Requested bean is currently in creation: Is there an…
  • commandButton/commandLink/ajax action/listener…
  • READ_EXTERNAL_STORAGE permission for Android
  • Understanding PrimeFaces process/update and JSF…
  • Error creating bean with name
  • Launching Spring application Address already in use
  • Autowiring two beans implementing same interface -…
  • Mock MQRFH2 header in JUnit Testing Error [MQRFH2…
  • Autowiring fails: Not an managed Type
  • Batch File: ( was unexpected at this time
  • IOException: read failed, socket might closed -…
  • Examples of GoF Design Patterns in Java's core libraries
  • Pentaho Data Integration SQL connection
  • SQLException: No suitable Driver Found for…
  • Why does Spring security throw exception…
  • javax.el.PropertyNotFoundException: Property 'foo'…
  • SecurityException: Permission denied (missing…
  • Spring - No EntityManager with actual transaction…
  • Getting Null Object Reference when passing List View…
  • Error inflating class android.support.v7.widget.Toolbar?
  • What is the difference between canonical name,…
  • How can I pass selected row to commandLink inside…
  • spring autowiring with unique beans: Spring expected…
  • Gradle error: Execution failed for task…
  • How to use java.net.URLConnection to fire and handle…
  • How to pass type value to a variable with the type…
  • @Autowired - No qualifying bean of type found for dependency
  • How to resume Fragment from BackStack if exists
  • How do I pass multiple parameter in URL?
  • Spring Boot - Cannot determine embedded database…
  • How do I analyze a program's core dump file with GDB…
  • Get the name of an object's type
  • Vaadin Spring Boot - There was an exception while…
  • Spring Integration Dynamic XML through JAXB or other tool
  • JavaScript: Passing parameters to a callback function
  • How to make a redirection on page load in JSF 1.x
  • java.lang.ClassNotFoundException: HttpServletRequest
  • fasm x64 windows gdi programming struggles - call to…
  • How do I keep only the first map and when the game…
  • Making Make Automatically Compile Objs from Headers…
  • can't access getters in store module
  • how to get the extender or implementer child's Type
  • Azure Availability Zone ARM Config
  • Spring Security exclude url patterns in security…
  • Name [jdbc/mydb] is not bound in this Context
  • SQL Error: 0, SQLState: 08S01 Communications link failure
  • Eclipse fails to open .vue files in Web Page Editor
  • org.springframework.beans.factory.UnsatisfiedDepende…
  • How to extract URL parameters from a URL with Ruby or Rails?
  • TLS 1.3 server socket with Java 11 and self-signed…
  • Row was updated or deleted by another transaction…
  • Who sets response content-type in Spring MVC (@ResponseBody)
  • how to get javaScript event source element?
  • Execution failed for task…
  • Bean must be of 'javax.sql.DataSource' type,…
  • @Autowired - No qualifying bean of type found for…
  • ClassNotFoundException thrown
  • Things possible in IntelliJ that aren't possible in Eclipse?
  • Why does my Spring Boot App always shutdown…
  • could not extract ResultSet in hibernate
  • My Application Could not open ServletContext resource
  • What's causing my java.net.SocketException:…
  • Many to Many org.hibernate.MappingException
  • How do I use reflection to invoke a private method?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How can the Euclidean distance be calculated with NumPy?

Next Post:

What does the explicit keyword mean?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error