Java中獲得了方法名稱的字符串,怎么樣調用該方法

問題: Java中獲得了方法名稱的字符串,怎么樣調用該方法

如果我有以下兩個變量

Object obj;
String methodName = "getName";

在不知道obj的類的情況下,我怎么樣才能調用該類的名叫methodName的方法呢?

這個方法被調用時不帶參數,并且返回的是一個字符串,這是一個Javabean的getter方法

回答一

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

這里的參數由你需要的具體的方法(如果有幾個重載方法的話,如果沒有參數就只需要給出方法名)決定

然后你就可以這樣調用方法了

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

再次聲明,如果你這個方法沒有參數,就忽略arg1,arg2.

回答二

通過反射實現方法的調用:

Class<?> c = Class.forName("class name");
Method method = c.getDeclaredMethod("method name", parameterTypes);
method.invoke(objectToInvokeOn, params);

“class name” 是類名

objectToInvokeOn是調用其方法的對象類型

method name 是你想要調用的方法名

parameterTypes是一個聲明了方法接收參數的Class[]

params 是聲明了傳給參數的Object[]

回答三

這個方法可以這樣被調用。可能會有更多的選擇(查一下反射的APi吧),但是這個是最簡單的

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;import org.junit.Assert;
import org.junit.Test;public class ReflectionTest {private String methodName = "length";private String valueObject = "Some object";@Testpublic void testGetMethod() throws SecurityException, NoSuchMethodException, IllegalArgumentException,IllegalAccessException, InvocationTargetException {Method m = valueObject.getClass().getMethod(methodName, new Class[] {});Object ret = m.invoke(valueObject, new Object[] {});Assert.assertEquals(11, ret);}}

回答四

首先,請避免這種代碼的的順序。它真的是很差的并且也不安全。(請看第二版的Secure Coding Guidelines for the Java Programming Language的第六節)

文章翻譯自Stack Overflow:https://stackoverflow.com/questions/160970/how-do-i-invoke-a-java-method-when-given-the-method-name-as-a-string

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391051.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391051.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391051.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

經驗主義 保守主義_為什么我們需要行動主義-始終如此。

經驗主義 保守主義It’s been almost three months since George Floyd was murdered and the mass protests. Three months since the nationwide protests, looting and riots across America.距離喬治弗洛伊德(George Floyd)被謀殺和大規模抗議活動已經快三個月了。 全國抗議…

Begin

Hello everyone, Finally,a technician from feiyang help me solve the question. Even though it is not the linux version i want.emmm...linux mint a new one i dont know about it And, lets make the life regular and delicate轉載于:https://www.cnblogs.com/lxc-run…

redis介紹以及安裝

一、redis介紹 redis是一個key-value存儲系統。和Memcached類似&#xff0c;它支持存儲的values類型相對更多&#xff0c;包括字符串、列表、哈希散列表、集合&#xff0c;有序集合。 這些數據類型都支持push/pop、add/remove及取交集并集和差集及更豐富的操作&#xff0c;而且…

java python算法_用Java,Python和C ++示例解釋的搜索算法

java python算法什么是搜索算法&#xff1f; (What is a Search Algorithm?) This kind of algorithm looks at the problem of re-arranging an array of items in ascending order. The two most classical examples of that is the binary search and the merge sort algor…

Java中怎么把文本追加到已經存在的文件

Java中怎么把文本追加到已經存在的文件 我需要重復把文本追加到現有文件中。我應該怎么辦&#xff1f; 回答一 你是想實現日志的目的嗎&#xff1f;如果是的話&#xff0c;這里有幾個庫可供選擇&#xff0c;最熱門的兩個就是Log4j 和 Logback了 Java 7 對于一次性的任務&a…

python機器學習預測_使用Python和機器學習預測未來的股市趨勢

python機器學習預測Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works withou…

線程系列3--Java線程同步通信技術

上一篇文章我們講解了線程間的互斥技術&#xff0c;使用關鍵字synchronize來實現線程間的互斥技術。根據不同的業務情況&#xff0c;我們可以選擇某一種互斥的方法來實現線程間的互斥調用。例如&#xff1a;自定義對象實現互斥&#xff08;synchronize("自定義對象")…

Python數據結構之四——set(集合)

Python版本&#xff1a;3.6.2 操作系統&#xff1a;Windows 作者&#xff1a;SmallWZQ 經過幾天的回顧和學習&#xff0c;我終于把Python 3.x中的基礎知識介紹好啦。下面將要繼續什么呢&#xff1f;讓我想想先~~~嗯&#xff0c;還是先整理一下近期有關Python基礎知識的隨筆吧…

volatile關鍵字有什么用

問題&#xff1a;volatile關鍵字有什么用 在工作的時候&#xff0c;我碰到了volatile關鍵字。但是我不是非常了解它。我發現了這個解釋 這篇文章已經解釋了問題中的關鍵字的細節了&#xff0c;你們曾經用過它嗎或者見過正確使用這個關鍵字的樣例 回答 Java中同步的實現大多是…

knn 機器學習_機器學習:通過預測意大利葡萄酒的品種來觀察KNN的工作方式

knn 機器學習Introduction介紹 For this article, I’d like to introduce you to KNN with a practical example.對于本文&#xff0c;我想通過一個實際的例子向您介紹KNN。 I will consider one of my project that you can find in my GitHub profile. For this project, …

MMU內存管理單元(看書筆記)

http://note.youdao.com/noteshare?id8e12abd45bba955f73874450e5d62b5b&subD09C7B51049D4F88959668B60B1263B5 筆記放在了有道云上面了&#xff0c;不想再寫一遍了。 韋東山《嵌入式linux完全開發手冊》看書筆記轉載于:https://www.cnblogs.com/coversky/p/7709381.html

Java中如何讀取文件夾下的所有文件

問題&#xff1a;Java中如何讀取文件夾下的所有文件 Java里面是如何讀取一個文件夾下的所有文件的&#xff1f; 回答一 public void listFilesForFolder(final File folder) {for (final File fileEntry : folder.listFiles()) {if (fileEntry.isDirectory()) {listFilesFor…

github pages_如何使用GitHub Actions和Pages發布GitHub事件數據

github pagesTeams who work on GitHub rely on event data to collaborate. The data recorded as issues, pull requests, and comments become vital to understanding the project.在GitHub上工作的團隊依靠事件數據進行協作。 記錄為問題&#xff0c;請求和注釋的數據對于…

c# .Net 緩存 使用System.Runtime.Caching 做緩存 平滑過期,絕對過期

1 public class CacheHeloer2 {3 4 /// <summary>5 /// 默認緩存6 /// </summary>7 private static CacheHeloer Default { get { return new CacheHeloer(); } }8 9 /// <summary>10 /// 緩存初始化11 /// </summary>12 …

python 實現分步累加_Python網頁爬取分步指南

python 實現分步累加As data scientists, we are always on the look for new data and information to analyze and manipulate. One of the main approaches to find data right now is scraping the web for a particular inquiry.作為數據科學家&#xff0c;我們一直在尋找…

Java 到底有沒有析構函數呢?

Java 到底有沒有析構函數呢&#xff1f; ? ? Java 到底有沒有析構函數呢&#xff1f;我沒能找到任何有關找個的文檔。如果沒有的話&#xff0c;我要怎么樣才能達到一樣的效果&#xff1f; ? ? ? 為了使得我的問題更加具體&#xff0c;我寫了一個應用程序去處理數據并且說…

關于雙黑洞和引力波,LIGO科學家回答了這7個你可能會關心的問題

引力波的成功探測&#xff0c;就像雙黑洞的碰撞一樣&#xff0c;一石激起千層浪。 關于雙黑洞和引力波&#xff0c;LIGO科學家回答了這7個你可能會關心的問題 最近&#xff0c;引力波的成功探測&#xff0c;就像雙黑洞的碰撞一樣&#xff0c;一石激起千層浪。 大家興奮之余&am…

如何使用HTML,CSS和JavaScript構建技巧計算器

A Tip Calculator is a calculator that calculates a tip based on the percentage of the total bill.小費計算器是根據總賬單的百分比計算小費的計算器。 Lets build one now.讓我們現在建立一個。 第1步-HTML&#xff1a; (Step 1 - HTML:) We create a form in order to…

用于MLOps的MLflow簡介第1部分:Anaconda環境

在這三部分的博客中跟隨了演示之后&#xff0c;您將能夠&#xff1a; (After following along with the demos in this three part blog you will be able to:) Understand how you and your Data Science teams can improve your MLOps practices using MLflow 了解您和您的數…

[WCF] - 使用 [DataMember] 標記的數據契約需要聲明 Set 方法

WCF 數據結構中返回的只讀屬性 TotalCount 也需要聲明 Set 方法。 [DataContract]public class BookShelfDataModel{ public BookShelfDataModel() { BookList new List<BookDataModel>(); } [DataMember] public List<BookDataModel>…