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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/891071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:45:21  来源:igfitidea点击:

Java Reflection getDeclaredMethod() with Class Types

javareflection

提问by Nate

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

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

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

例如,如何解决下面的“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");
        }
    }
}

采纳答案by coobird

params[0] = String.class;

Using classon Stringwill return the Class<?>that is associated with the Stringclass.

使用classonString将返回Class<?>String类关联的。