java - getMethods 是否可以按顺序使用反射?

标签 java reflection

<分区>

Possible Duplicates:
Java Reflection: Getting fields and methods in declaration order
Java. Get declared methods in order they apear in source code

假设我有这门课

是否可以按顺序使用 getter 方法?

public class ClassA {

private String name;
private Integer number;
private Boolean bool;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Integer getNumber() {
    return number;
}

public void setNumber(Integer number) {
    this.number = number;
}

public Boolean getBool() {
    return bool;
}

public void setBool(Boolean bool) {
    this.bool = bool;
}

我试过了..

for (Method method : ClassA.class.getDeclaredMethods()) {
    if (!(method.getReturnType().toString().equals("void"))) {
        method.invoke(obj, new Object[0])));
    }
}

我从文档中得到的

...The elements in array returned are not sorted and are not in any particular order...

那么..就是这样吗?是否存在一些替代方案,或者我只需要实现一些东西?

最佳答案

您可以向每个方法添加您自己的@annotation,其中包含一个数字。然后获取所有 getter 方法,并使用您的自定义排序器根据您使用 Collections.sort() 传递给注释的数字对它们进行排序。

例如:

@SortedMethod(100)
public String getName()
{
    return name;
}

@SortedMethod(200)
public String getNumber()
{
    return number;
}

关于java - getMethods 是否可以按顺序使用反射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6996910/

相关文章:

java - 限制 Varnish 客户端等待时间,而不是后端时间

c# - 使用反射设置值 - 转换错误

.net - Powershell 从字符串中生成 System.Type

c# - 具有不同返回类型的重载函数缺少 MethodInfo

c# - 如何动态找出所有具有自定义属性的方法

java - 根据软件许可证标志更改 JAAS 角色

Java 垃圾收集器 - 它什么时候收集?

java - 迭代器和 ConcurrentModificationException

java - A Double 中有多少位小数(Java)

java - 此方法返回的对象实例是什么?