java内省(introspection)查找类的成员

标签 java introspection

我正在尝试通过 Object 对象的名称 memberName 访问其属性。

我尝试过:

new PropertyDescriptor(memberName,object.getClass()).getReadMethod().invoke(object);

它适用于我的对象的大多数属性。但其中一些是 boolean 值,并且 getter 的形式是“isValid”而不是“getValid”,上面的代码会产生 IntrospectionException 错误。

如果可能的话,在不使用更多代码/外部库的情况下,我该怎么做才能完成这项工作?

<小时/>

编辑:

是的,抱歉,我忘了提及,我类的成员的名字可能选得不好。它已经是“boolean isValid”,并且 getter 也是“isValid”。

最佳答案

它对我来说效果很好,它是 documented这就是它的工作原理:

Constructs a PropertyDescriptor for a property that follows the standard Java convention by having getFoo and setFoo accessor methods. Thus if the argument name is "fred", it will assume that the writer method is "setFred" and the reader method is "getFred" (or "isFred" for a boolean property). Note that the property name should start with a lower case character, which will be capitalized in the method names.

(强调我的。)

示例代码:

import java.beans.*;

public class Test {

    public static void main(String[] args) throws Exception {
        Test test = new Test();
        PropertyDescriptor pd = new PropertyDescriptor("checked", Test.class);
        System.out.println(pd.getReadMethod().invoke(test));
    }

    public boolean isChecked() {
        System.out.println("isChecked called!");
        return true;
    }

    public void setChecked(boolean checked) {
    }
}

我建议您尝试我的示例代码,如果它适合您,然后看看您是否可以找到我的代码和您的代码之间的差异。

关于java内省(introspection)查找类的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15273588/

相关文章:

Ruby 方法自省(introspection)

python - 如何获得原始订单中的字段?

ruby - 内省(introspection)模块类时 "#map(&proc)"习惯用法如何工作?

objective-c - 在运行时检查 ObjC 属性是否可为空

node.js - 如何在 Graphql 中删除内省(introspection)查询的身份验证

java - hibernate 3.6.7 orphanRemoval 级联单向

java - 该行返回什么?

java - 套接字和对象输入流

java - 我如何获得 Java JUnit 中的大纲规范?

java - 聊天客户端发生奇怪的线程