【发布时间】:2016-06-24 16:17:13
【问题描述】:
假设我有以下课程:
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);
}
我知道我可以创建一个通用方法,它接受任何扩展 X 的列表,我可以在那里迭代每个列表并调用 getCount()。但我也希望能够迭代一个类的方法。有什么方法可以实现吗?
我知道我可以通过反射获得 getter 方法的列表。但我不知道在这种情况下如何使用它。
顺便说一句,这个问题不是关于如何使用反射获取方法列表。更多的是关于如何使用它或反射是如何工作的。
【问题讨论】:
标签: java reflection