带有类类型的Java反射getDeclaredMethod()

时间:2009-05-21 01:51:28

标签: java reflection

我正在尝试理解Java反射,并且在使用非整数setter方法时遇到了困难。

举个例子,如何解决下面的“getDeclaredMethod()”调用?

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");
        }
    }
}

1 个答案:

答案 0 :(得分:22)

params[0] = String.class;

class上使用String将返回与Class<?>类关联的String