简体   繁体   中英

Java Reflection Output

I was given the following assignment:

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.

My working code for this assignment is:

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

This works, but my output looks like this:

foo(A, int, double) -> void
bar(A, int, double, char) -> int
doo(A) -> double

How do I change this to make the output look like what is asked for?

If i understand you correctly, your only problem is having the class type as first parameter in the static doo() method.

You may use the Modifier.isStatic() method to check this:

     boolean isStatic = Modifier.isStatic(y.getModifiers());
     System.out.print(y.getName() + "("
                         + (isStatic ? "" : y.getDeclaringClass().getSimpleName()));

You'll have to get rid of the additional comma then, but this shouldn't be to hard ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM