Search code examples
javaintrospection

java introspection to find member of the class


I'm trying to access the attribute of an Object object through its name memberName.

I tried:

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

It works well for most of the attributes of my Object. But some of them are booleans, and the getter is of the form 'isValid' instead of 'getValid' and the above code produces a IntrospectionException error.

What could I do to make this work, if possible without using much more code / external libraries ?


edit :

yes sorry I forgot to mention that the name of the member of my class is perhaps poorly chosen. It is already 'boolean isValid' and the getter is also 'isValid'.


Solution

  • It works fine for me, and it's documented that that's how it's meant to work:

    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.

    (Emphasis mine.)

    Sample code:

    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) {
        }
    }
    

    I suggest you try my sample code, and if that works for you then see if you can find the difference between my code and your code.