Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reflection getDeclaredMethod() with Class Types

Tags:

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");
        }
    }
}
like image 719
Nate Avatar asked May 21 '09 01:05

Nate


1 Answers

params[0] = String.class;

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

like image 189
coobird Avatar answered Sep 23 '22 13:09

coobird