views:

2008

answers:

1

I'm trying to understand Java reflecton and am encountering difficulties when working with non-Integer setter methods.

As an example, how can I resolve the "getDeclaredMethod()" call below?

import java.lang.reflect.*;

class Target {
    String value;

    public Target() { this.value = new String("."); }
    public void setValue(String value) { this.value = value; }
    public String getValue() { return this.value; }
}

class ReflectionTest {
    public static void main(String args[]) {
        try {
            Class myTarget = Class.forName("Target");

            Method myMethod;
            myMethod = myTarget.getDeclaredMethod("getValue");  // Works!
            System.out.println("Method Name: " + myMethod.toString());

            Class params[] = new Class[1];
            //params[0] = String.TYPE; // ?? What is the appropriate Class TYPE?
            myMethod = myTarget.getDeclaredMethod("setValue", params); // ? Help ?
            System.out.println("Method Name: " + myMethod.toString());

        } catch (Exception e) {
            System.out.println("ERROR");
        }
    }
}
+2  A: 
params[0] = String.class;

Using class on String will return the Class<?> that is associated with the String class.

coobird
Ugh. I'm an idiot. Thanks!
Nate
(Oops, I didn't mean to upvote the comment!)I just wanted to add that I wasn't aware of it to the other day, so it's not exactly that obvious.
coobird
One Question I have for you, in what scenario, I will try to know which methods are in the class and Variables? why I will try to know that? I am exploring the reasons for using this methods getDeclaredMethod(), getDeclaredFields() , etc... Can you please suggest
harigm