gpt4 book ai didi

Java 反射 : How to get methods with no parameters only

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:08:58 25 4
gpt4 key购买 nike

我正在做一项关于 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)方法列表”。有没有办法只列出没有参数的方法?我使用了 getMethods,但我最终从带有参数的 Object 和 Class 父类(super class)中获得了很多方法。

例如下面我写的代码:

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

输出如下:

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()

有没有办法只打印那些没有参数的?另外,我对作业细节的解释首先是正确的吗?还是短语“不指定参数的公共(public)方法”可能意味着其他意思,我的想法完全错误?

最佳答案

您看过方法类的 API 了吗?有一种方法叫做 getParameterTypes()有你正在寻找的答案,并且 API 明确说明如果没有参数将返回什么。只需在返回的方法上的 for 循环中调用它,您应该会像火石一样。

关于Java 反射 : How to get methods with no parameters only,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7755012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com