я получил следующее назначение:Java Reflection Выход
Write a method displayMethodInfo (as a method of a class of your choosing), with the following signature: static void displayMethodInfo(Object obj); The method writes, to the standard output, the type of the methods of obj. Please format the method type according to the example below. Let obj be an instance of the following class:
class A { void foo(T1, T2) { ... } int bar(T1, T2, T3) { ... } static double doo() { ... } }
The output of displayMethodInfo(obj) should be as follows:
foo (A, T1, T2) -> void bar (A, T1, T2, T3) -> int doo() -> double
As you can see, the receiver type should be the first argument type. Methods declared static do not have a receiver, and should thus not display the class type as the first argument type.
Мой рабочий код для этого задания является:
import java.lang.Class;
import java.lang.reflect.*;
class Main3 {
public static class A {
void foo(int T1, double T2) { }
int bar(int T1, double T2, char T3) { return 1; }
static double doo() { return 1; }
}
static void displayMethodInfo(Object obj)
{
Method methodsList[] = obj.getClass().getDeclaredMethods();
for (Method y : methodsList)
{
System.out.print(y.getName() + "(" + y.getDeclaringClass().getSimpleName());
Type[] typesList = y.getGenericParameterTypes();
for (Type z : typesList)
System.out.print(", " + z.toString());
System.out.println(") -> " + y.getGenericReturnType().toString());
}
}
public static void main(String args[])
{
A a = new A();
displayMethodInfo(a);
}
}
Это работает, но мой результат выглядит следующим образом:
foo(A, int, double) -> void
bar(A, int, double, char) -> int
doo(A) -> double
Как изменить это, чтобы сделать вывод похожим на то, что требуется?
Почему ты решите объявить параметры методов в 'A' как' int', 'double' и' char'? По-видимому, 'T1',' T2' и 'T3' назначения должны быть * типами *, а не * именами * параметров. Если вы ошиблись в предварительных требованиях, неудивительно, что результат тоже неправильный ... – Holger
Кстати, нет необходимости добавлять 'import' для' java.lang.Class' ... – Holger