java Java反射:如何仅获取没有参数的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7755012/
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-10-30 21:17:04  来源:igfitidea点击:

Java reflection: How to get methods with no parameters only

javareflection

提问by Jigglypuff

I'm working on a school assignment about Java reflection. The details are below:

我正在做一个关于 Java 反射的学校作业。详情如下:

Write a console program that asks the user for a class name, loads that class and creates an instance of it. We assume that the class has a constructor without any parameters. Then, the program prints out the names and values of the public variables of the created object, and also a list of the public methods that do not specify a parameter. The program should let the user choose a method and execute that method on the created object. Afterwards, the program should again show the public variables with their values and allow the user to choose a method, and so on. Use the following class to test your implementation:

public class Counter {
    public int c;
    public void increment() { c++; }
    public void decrement() { c--; }
    public void reset() { c = 0; }
}

编写一个控制台程序,询问用户一个类名,加载该类并创建它的一个实例。我们假设该类有一个没有任何参数的构造函数。然后,程序打印出所创建对象的公共变量的名称和值,以及未指定参数的公共方法列表。程序应该让用户选择一个方法并在创建的对象上执行该方法。之后,程序应该再次显示公共变量及其值,并允许用户选择方法,等等。使用以下类来测试您的实现:

public class Counter {
    public int c;
    public void increment() { c++; }
    public void decrement() { c--; }
    public void reset() { c = 0; }
}

The problem I am having has to do with the following sentence: "list of the public methods that do not specify a parameter". Is there a way to list only methods with no parameters? I have used getMethods but I end up getting a lot of methods from the Object and Class superclasses with parameters.

我遇到的问题与以下句子有关:“未指定参数的公共方法列表”。有没有办法只列出没有参数的方法?我已经使用了 getMethods,但我最终从带有参数的 Object 和 Class 超类中获得了很多方法。

For example the following code that I have written:

例如,我编写的以下代码:

import java.lang.reflect.*;
import java.io.*;

public class Q1 {
    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            System.out.print("What class would you like to run? ");
            String className = reader.readLine();

            Class c = Class.forName(className);
            Object o = c.newInstance();

            for (Field f : c.getFields())
                System.out.println(f);
            for (Method m : c.getMethods())
                System.out.println(m);

        } catch(IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

Outputs the following:

输出以下内容:

What class would you like to run? Counter
public int Counter.c
public void Counter.reset()
public void Counter.increment()
public void Counter.decrement()
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()

你想开什么课?Counter
public int Counter.c
public void Counter.reset()
public void Counter.increment()
public void Counter.decrement()
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public final void java.lang.Object.wait() 抛出 java.lang.InterruptedException
public final void java.lang.Object.wait(long,int) 抛出 java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang. Object)
public java.lang.String java.lang.Object.toString()
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()

Is there a way to get only the ones with no parameters to be printed? Also is my interpretation of the assignment details right in the first place? Or does the phrase "public methods that do not specify a parameter" possibly mean something else and I have entirely the wrong idea?

有没有办法只打印没有参数的那些?另外,我对作业细节的解释是否正确?或者“不指定参数的公共方法”这句话可能意味着其他什么而我完全错误的想法?

回答by Hovercraft Full Of Eels

Have you looked at the API for the Method class? There's a method called getParameterTypes()that has the answer for what you're looking for, and the API states explicitly what this will return if there are no parameters. Just call this in your for loop on the Methods returned and you should be in like flint.

您是否查看了 Method 类的 API?有一个名为getParameterTypes()的方法可以回答您要查找的内容,并且 API 明确说明如果没有参数将返回什么。只需在返回的方法的 for 循环中调用它,您就应该像燧石一样。

回答by Paul Sasik

Just use the Method class' getParameterTypesfunction. If the return value is 0 then there are no parameters to that function. Key part from the Java doc:

只需使用 Method 类的getParameterTypes函数即可。如果返回值为 0,则该函数没有参数。Java 文档中的关键部分:

getParameterTypes

public Class[] getParameterTypes()

Returns an array of Class objects that represent the formal parameter types, in declaration order, of the method represented by

this Method object. Returns an array of length 0 if the underlying method takes no parameters.

Returns:
    the parameter types for the method this object represents

获取参数类型

公共类[] getParameterTypes()

Returns an array of Class objects that represent the formal parameter types, in declaration order, of the method represented by

这个方法对象。如果底层方法不带参数,则返回长度为 0 的数组。

Returns:
    the parameter types for the method this object represents