[英]How to iterate over methods of a class and then iterate over returned object and call another method ?
可以說我有以下課程:
public class ExampleList{
// fields
List<A> getAList(){}
List<B> getBList(){}
List<C> getCList(){}
//A, B and C all extends class X with field num
}
public class Example{
ExampleList getExampleList(){}
}
public class Test{
main(){
Example example = //from somewhere I get object;
List<A> lA = example.getExampleList().getAList();
List<B> lB = example.getExampleList().getBList();
List<C> lC = example.getExampleList().getCList();
//Currently I am doing
if(lA != null) {
//iterate and call getCount(num)
if(lB != null) {
//iterate and call getCount(num)
if(lC != null) {
//iterate and call getCount(num)
}
getCount(int num) { //do something }
}
我想做的是動態遍歷ExampleList的所有方法,並只調用一次getCount(num)。 喜歡:
main(){
for ( Methods mList : Methods)
for ( X x: mList )
getCount(x.getNum);
}
我知道我可以創建一個通用方法,該方法接受List擴展X的任何內容,並且可以在那里迭代每個List並調用getCount()。 但我也希望能夠遍歷類的方法。 有沒有辦法可以做到這一點?
我知道我可以通過反射獲取吸氣方法列表。 但是我不知道如何在這種情況下使用它。
順便說一句,這個問題不是關於如何從使用反射中獲取方法列表。 它更多地是關於如何使用它或反射如何工作的。
遍歷給定類的方法:
// Get the instance of the class
X instance = X.class.newInstance();
// Run through all methods of the class
for(Method m : instance.getClass().getDeclaredMethods()) {
// The first parameter of invoke is an instance of X
// The second parameters are the parameters to pass to the method
m.invoke(instance, new Object[]{});
}
// do the call to getCount
getCount();
如果您有List <X>,請多次調用。
對於使用反射,起點是https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html
希望能幫助到你 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.