#前提: 一个对象有a1, a2,....a100等属性
#期望:要获取a20 到 a50这30个属性值,如果通过手动getA20到getA50代码量比较大,是否可以通过更优雅的方式实现?(可以以Java为例回答,真实需求是Kotlin语言实现)
这个你可以考虑用反射
例子
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws Exception {
A a = new A();
// 获取 A 类的 Class 对象
Class clazz = A.class;
// 循环调用 getA20 - getA50 方法
for (int i = 20; i <= 50; i++) {
String methodName = "getA" + i;
Method method = clazz.getMethod(methodName);
int result = (int) method.invoke(a);
System.out.println("调用 " + methodName + " 方法的结果为:" + result);
}
}
}
class A {
public int getA20() {
return 20;
}
public int getA21() {
return 21;
}
public int getA22() {
return 22;
}
// ...
public int getA50() {
return 50;
}
}
Kotlin版
import kotlin.reflect.full.memberFunctions
fun main() {
val a = A()
// 获取 A 类的 KClass 对象
val clazz = A::class
// 循环调用 getA20 - getA50 方法
for (i in 20..50) {
val methodName = "getA$i"
val method = clazz.memberFunctions.firstOrNull { it.name == methodName } ?: error("Method $methodName not found")
val result = method.call(a) as Int
println("调用 $methodName 方法的结果为:$result")
}
}
class A {
fun getA20(): Int {
return 20
}
fun getA21(): Int {
return 21
}
fun getA22(): Int {
return 22
}
// ...
fun getA50(): Int {
return 50
}
}
不知道你这个问题是否已经解决, 如果还没有解决的话: