Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reflection: How to get methods with no parameters only

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

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

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.

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

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?

like image 576
Jigglypuff Avatar asked Oct 13 '11 13:10

Jigglypuff


2 Answers

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.

like image 156
Hovercraft Full Of Eels Avatar answered Sep 18 '22 11:09

Hovercraft Full Of Eels


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

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
like image 41
Paul Sasik Avatar answered Sep 18 '22 11:09

Paul Sasik